[英]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.