-1

I want to design a program that inputs a string with space and output split string and the number of letters, but I don't know what the "word[]" means in "while (!ss.eof()){}". For example, I input "Programming is fun", the result is

Programming
is
fun
Length:18

While I change "word[i]" to word[0] the result is

fun


Lenght:18

word[1] is


fun

Lenght:18

Could someone explain it?

Here is my code:

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

void printStringArray(string word[], int size)
{
    for (int i = 0;i < size;i++)
    {
        cout << word[i] << endl;
    }
}

int main()
{
    string word[10];
    string str;
    getline(cin, str);
    stringstream ss(str);
    int i = 0;
    while (!ss.eof())
    {
        ss >> word[i];//P
        i++;
    }
    printStringArray(word, 3);
    cout << "Lenght:" << str.size();

    return 0;
}
timeil0611
  • 23
  • 3
  • Does this answer your question? [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Jeffrey Apr 09 '21 at 23:15
  • 1
    You should use a debugger an step through your code. After you make changes, the behavior should be obvious. Otherwise, use pen and paper to write down variables and their values as you go through the program. – Thomas Matthews Apr 09 '21 at 23:18

1 Answers1

0

This loop:

while (!ss.eof())
{
    ss >> word[0];
    i++;
}

sets the first item in your array to 3 different values, at each iteration the value gets replaced with a new one, so you are left with the last word in the first position of your array, with the other entries being unset (empty).

When you change word[0] with word[1] the same thing happens except in the 2nd position of your array.

zdan
  • 25,964
  • 5
  • 54
  • 67
  • Side note: You'll get away with it here because the last word found in `ss` will terminate when it hits the end of the stream, but under normal circumstances, [looping on EOF is a bug](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). Use `while (ss >> word[i]) { i++; }` instead to read, test that the read found data, and then act on what was read. – user4581301 Apr 09 '21 at 23:28
  • 1
    Actually, I can't be so sure that this use is safe from the bug. If the user inputs a line with one or more trailing spaces, the count will be off and a bad value will go into the array.. – user4581301 Apr 09 '21 at 23:31