Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在每个单词都是字符串数组的情况下输入句子,直到用户按enter键_C++_String_Cin - Fatal编程技术网

C++ 如何在每个单词都是字符串数组的情况下输入句子,直到用户按enter键

C++ 如何在每个单词都是字符串数组的情况下输入句子,直到用户按enter键,c++,string,cin,C++,String,Cin,我必须输入一个句子,例如:-猫吃老鼠。句子的每个单词都应该存储在字符串s[]的数组中。因此,s[0]=The,s[1]=cat s2=ate等等。在用户按下enter键之前,应一直输入单词 我尝试了多种方法,其中大多数在我的机器上工作(使用终端),用于n个测试用例,但它在在线判断中显示了运行时错误,如CodeChef /* Below is the method I tried. Test case showing RUNTIME ERROR is:- 3 (No of test cases

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

我尝试了多种方法,其中大多数在我的机器上工作(使用终端),用于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;
                }

您可以使用以下简单循环来分隔输入字符串:

#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

您可以使用以下简单循环来分隔输入字符串:

#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

您可以使用std::getline,然后使用std::istringstream。@Vladfrommoskow非常感谢您,但是,如果您能编写一个对循环有很大帮助的大纲,我就无法实现它。您可以使用std::getline,然后使用std::istringstream。@Vladfrommoskow非常感谢您,如果你能写一个对我有很大帮助的循环大纲,我就无法实现它。为什么知道只有五个字?@Vladfrommosco不是,我只是举了五个字为例,他可以放任何他想要的尺寸,甚至可以使尺寸动态化,我只是不想让代码复杂化。我主要关注的是将字符串分割成一束更小的字符串。为什么我们知道有五个单词?@Vladfrommosco不是,我只是举了五个例子,他可以任意大小,甚至可以动态调整大小,我只是不想让代码复杂化。我主要关注的是将字符串分成一组较小的字符串