1

I want to input a string array in C++. For example:

 name[]={"jun","hua","kyu",..}
              cout<<name[2];

output: hua

This is my code but the string that I input doesn't stop. I don't know how to fix it. Please, help me. Thank you.

 string name[50];
string st;
int i=0;
    do{
            cin>>st;
            name[i]=st;
            i++;    
        } while (st!="\0");
6
  • Use std::vector Commented Dec 4, 2013 at 16:43
  • the string that I input doesn't stop What do you mean? Commented Dec 4, 2013 at 16:44
  • 2
    Also, I would have expected your sample code to output kyu, not hua Commented Dec 4, 2013 at 16:45
  • 1
    output: hua No, output: kyu Commented Dec 4, 2013 at 16:45
  • Wait a second. Are you trying to read from std::cin the strings you write in std::cout in the same program? Commented Dec 4, 2013 at 16:53

6 Answers 6

2

You should put std::cin in the condition of a while loop, this way when ever it fails (which it will when you reach a null terminating string) it will return false and it will leave the loop.

Here is an example using std::vector

#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::vector<std::string> userInputVec;
    std::string input;
    while(std::cin >> input)
    {
        userInputVec.push_back(input);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Not "inside of a while loop", but in the condition of a while loop (as you do in your example).
@JamesKanze Rockie mistake. Fixed.
1

Formatted input, cin>>st will skip over all whitespace (including blank lines), and give you the first word it finds.

I'm guessing you want to stop when there's a blank line. You could do something like this, to read entire lines:

while (i < 50 && getline(cin, st) && !st.empty()) {
    name[i] = st;
    i++;
}

If you want to read individual words, and allow multiple words on a line, then parse each line after reading it:

while (i < 50 && getline(cin, st) && !st.empty()) {
    std::stringstream ss(st);
    std::string word;
    while (i < 50 && ss >> word) {
        name[i] = word;
        ++i;
    }
}

You should consider using std::vector<string> name;, rather than a fixed-size array, and adding names with push_back(), to avoid the ugly range checks in my code or the possibility of horrific stack-corruption bugs in yours.

5 Comments

While your code doesn't suffer from the problem, you don't mention why his code doesn't work: the fact that once he reaches end of file, std::cin >> st will fail, probably without changing st, so he will loop forever.
@JamesKanze: Indeed, I was assuming that the OP's code was trying to look for a blank line, rather than the end of a (redirected) file, and couldn't be bothered to write a complete essay on how to use the I/O library.
To be frank, I'm not too sure what the OP is trying to do. What is clear is that he never checks whether the input succeeds, and has an endless loop (unless somehow he's managed to get a '\0' character in the input).
@JamesKanze: You're right that it's unclear what's wanted; I just wrote something that might be vaguely helpful, if my guesses are somewhere near the mark. "\0" will be interpreted as an empty string, not a \0 character; hence my guess that that's what the OP was trying to check for.
And I'd missed that: for some reason, I was thinking that "\0" would be a string (std::string) with a '\0' character in it, which of course, it wouldn't be. I wonder why he wrote "\0" for "", though.
1

It's not clear to me what you're trying to do. If the entire contents of the file are "kyu", then the input definitely will stop when it reaches end of file. What I suspect (but I'm really just guessing) is that you've output the strings without a separator, and so the input doesn't know where each string ends, and reads all of the characters as a single string. In other words, your output file contains "junhuakyu...".

When outputting strings (and a lot of other things) as text, you must find some way of deliminating them. If the strings use a restricted character set (e.g. just letters), it's often sufficient to just insert a separator character between each string, choosing one which cannot appear in the strings. For example:

for ( auto p = std::begin(name); p != std::end(name); ++ p ) {
    if ( p != std::begin(name) ) {
        std::cout << ' ';
    }
    std::cout << *p;
}

This will give you something like "jun hua kyu ..." in the file, which can easily be read using:

std::string st;
while ( std::cin >> st ) {
    //  ...
}

Which brings up a secont problem with your code. You're using the results of what you've read without testing whether the read succeeded. If it fails (e.g. because of end of file), then st may not have been modified; at any rate, if the file is a text file, and really only contains text, you'll never get st == "\0"; this can only occur if the file actually contains a '\0' character (which isn't legal if it is a text file).

Finally, of course: the choice of separator is up to you. White space is particularly simple; if the strings can contain blanks, you might choose '\n', and use std::getline to read. And if worse comes to worse, and the strings can be literally anything, you'll have to implement some sort of quoting mechanism, possibly with escape characters.

Comments

1

Use a vector of strings:

std::vector<std::string> strings;

Read strings into strings:

for(std::string s; std::cin >> s;)
    strings.push_back(std::move(s));

Print out strings:

for(auto& s : strings)
    std::cout << s << '\n';

1 Comment

FWIW: if std::cin >> s succeeds, s will never be empty.
0

Do you send a null character in the input stream of your program? I guess you don't, so a better way to write your loop would be:

while ( std::cin >> st ) {
    name[i] = st;
    ++i;
}

std::istream::operator>>() returns the read stream. If it could not read the requested type, the stream will have a fail bit turned on and will result to false when casted as a boolean.

Also, you should check the value of i not to write outside name.

Comments

0

i hope it will help uu

string name[50];
string st;
int i=0;
    do{
            cin>>st;
            name[i]=st;
            i++;    
        } while (st!="\n");

or use

string name[50];
string st;
int i=0;
    do{

            getline(cin,name[i]);
            i++;    
        } while (i<50);

1 Comment

Neither of these will work. In the first, std::cin >> st will never put a '\n' in st. By definition. In the second, at some point, you'll reach end of file, std::getline will fail, and may or may not change name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.