如何输入每个单词都在字符串数组中的句子,直到用户按下回车键

How to take input of a sentence where each word is in a string array, untill user presses enter

我必须输入一个句子,例如:- The cat ate mouse。句子中的每个单词都应该存储在一个字符串数组 s[] 中。因此,s[0]=The,s[1]=cat s2=ate 等等。在用户按下回车键之前,应该输入单词。

我尝试了多种方法,大多数方法都可以在我的机器上(使用终端)运行 n 个测试用例,但它在像 CodeChef 这样的在线判断中显示运行时错误。

/*
Below is the method I tried. Test case showing RUNTIME ERROR is:-
3   (No of test cases)        
vbc def ghij alpha
This will test your coding skills
Peter Piper picked a peck of pickled peppers
*/

原来的问题是将句子中的单词按词汇顺序排序。

while(ch!='\n')
                {
                        cin>>s[i];
                        i++;
                        scanf("%c", &ch);
                        //cout<<"hi"<<endl;
                        if(ch=='\n')
                                break;
                }

我检查过我的排序算法工作正常,问题出在输入上。 第2句代码生成Infinite no of HI's did as debugging语句后,暗示while循环在那里无限运行。

/*Output was:-
 hi
 hi
 hi
 hi
 alpha ghij def vbc 
 hi
 hi
 hi
 hi
 hi
 hi
 skills coding your test will This 
 hi
 hi
 hi
 hi
 hi
 hi..... Infinitely*/

您可以像这样使用一个简单的循环来分隔输入字符串:

#include <iostream>
#include <string>
using namespace std;
int main(){
 string S;
 string strings[5]; // whatever the size
 unsigned index = 0;

 getline(cin, S);
 for (unsigned i = 0; i < S.size(); i++)
 {
    if (S[i] == ' ')
        index++;
    else
        strings[index] += S[i];
 }

 for (unsigned i = 0; i < 5; i++)  // whatever the size again
    cout << strings[i] << endl;
}

输入:

I like big yellow birds

输出:

I
like
big
yellow
birds