[英]How do I take an input in C++ and “split” it into a list? In other words, take N inputs and put in into an array of N length
[英]I want to take user input and put it into an array of strings c++
我想接受用户输入并将他们键入的内容放入字符串数组中。 我希望它读取每个字符并用空格分隔每个单词。 我相信这是不好的编码,尽管我确实尝试过得体。 我遇到了细分错误错误,并且想知道如何才能在没有错误的情况下执行此操作。 这是我的代码。
#include <iostream>
using namespace std;
void stuff(char command[][5])
{
int b, i = 0;
char ch;
cin.get(ch);
while (ch != '\n')
{
command[i][b] = ch;
i++;
cin.get(ch);
if(isspace(ch))
{
cin.get(ch);
b++;
}
}
for(int n = 0; n<i; n++)
{
for(int m = 0; m<b; m++)
{
cout << command[n][m];
}
}
}
int main()
{
char cha[25][5];
char ch;
cin.get(ch);
while (ch != 'q')
{
stuff(cha);
}
return 0;
}
b
未初始化,因此在首次用作索引时将具有随机值。 初始化b
并确保数组索引不超出数组的范围。
或者,使用std::vector<std::string>
和operator>>()
并忽略数组索引:
std::string word;
std::vector<std::string> words;
while (cin >> word && word != "q") words.push_back(word);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.