gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:48 24 4
gpt4 key购买 nike

例如,我必须输入一个句子:- 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

关于c++ - 如何输入每个单词都在字符串数组中的句子,直到用户按下回车键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com