0

I've been doing programming challenges on coderbyte and while doing one, ran into an issue. I want to isolate a word from a string, do some checks on it and then move to another word. The code I'm going to post is supposed to take only the first word and print it out on the screen. When I run it, it doesn't print anything. I thought that maybe I did something wrong in the while loop so I did a simple test. Let's say my input is "This is a test sentence" and instead of word (in cout), I type word[0]. Then it prints "T" just fine. Can you find what the problem is?

#include <iostream>
#include <string>
using namespace std;

int Letters(string str) {
    int i=0;
    int len=str.length();
    string word;
    while(i<len){
        if(isspace(str[i])){word[i]='\0'; break;}
        word[i]=str[i];
        i++;
    }
    cout<<word;
    return 0;
}

int main() {
    int test;
    string str;
    getline(cin, str);
    test=Letters(str);
    return 0;
}
2
  • 2
    Change word[i]=str[i]; to word.append(str[i]);. You didn't preserve space for word, so you can't access word[i]. Commented Sep 24, 2014 at 15:14
  • 1
    You have undefined behavior. Hint - word[i]=str[i] Commented Sep 24, 2014 at 15:14

2 Answers 2

5
string word;

is default constructed, which is empty initially. Inside while loop, you tried to do:

word[i] = str[i];

It means you tried to access memory that has not been allocated,resulting in undefined behavior.

Try:

word.append(str[i]); 
Sign up to request clarification or add additional context in comments.

1 Comment

word[i]='\0'; should be removed too.
1

You can use simpler way to get words from input in C++. It will help you to avoid errors in the future.

#include <iostream>
using namespace std;

int main()
{
  string word;
  while(cin >> word)
    {
      // "word" contains one word of input each time loop loops
      cout << word << endl;
    }
  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.