C++ 我希望获取用户输入并将其放入字符串数组c++;
我希望接收用户输入,并将他们键入的内容放入字符串数组中。我想让它读每个字符,并用空格分隔每个单词。我相信这是编码不好,虽然我确实试图做得体面。我得到了一个分割错误,我想知道我怎么可以不得到错误继续这样做。这是我的密码C++ 我希望获取用户输入并将其放入字符串数组c++;,c++,C++,我希望接收用户输入,并将他们键入的内容放入字符串数组中。我想让它读每个字符,并用空格分隔每个单词。我相信这是编码不好,虽然我确实试图做得体面。我得到了一个分割错误,我想知道我怎么可以不得到错误继续这样做。这是我的密码 #include <iostream> using namespace std; void stuff(char command[][5]) { int b, i = 0; char ch; cin.get(ch); while
#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;
}
#包括
使用名称空间std;
void stuff(char命令[][5])
{
int b,i=0;
char ch;
cin.get(ch);
而(ch!='\n')
{
命令[i][b]=ch;
i++;
cin.get(ch);
if(isspace(ch))
{
cin.get(ch);
b++;
}
}
for(int n=0;nb
未初始化,因此首次用作索引时将有一个随机值。初始化b
并确保数组索引不超出数组的边界
或者,使用and运算符>>()
并忽略数组索引:
std::string word;
std::vector<std::string> words;
while (cin >> word && word != "q") words.push_back(word);
std::字符串字;
向量词;
while(cin>>word&&word!=“q”)字。推回(word);
b
未初始化,因此第一次用作索引时会有一个随机值。初始化b
并确保数组索引不会超出数组的边界
或者,使用and运算符>>()
并忽略数组索引:
std::string word;
std::vector<std::string> words;
while (cin >> word && word != "q") words.push_back(word);
std::字符串字;
向量词;
while(cin>>word&&word!=“q”)字。推回(word);
为什么不使用std::vector>
并将cin
应用于字符串?为什么不使用std::vector>
并将cin
应用于字符串?谢谢!每当我使用空格时,数组中都会出现奇怪的字符。你知道如何解决这个问题吗?谢谢!每当我使用空格时,数组中都会出现奇怪的字符。你知道怎样才能解决这个问题吗?