C++,如何获得多个输入除以空白

C++, How to get multiple input divided by whitespace?

本文关键字:输入 空白 何获得 C++      更新时间:2023-10-16

我有一个程序需要获取多个cstring。我现在一次输入一个,然后问你是否想输入另一个单词。我找不到任何简单的方法来只获得一个单词被划分为空白的输入。即"一二三",并将输入保存在cstrings数组中。

typedef char cstring[20]; cstring myWords[50];

目前,我正在尝试使用getline并将输入保存到cstring中,然后我尝试使用string.h库来操作它。这是正确的方法吗?否则怎么办?

如果您真的必须使用c样式字符串,您可以使用istream::getlinestrtokstrcpy函数:

typedef char cstring[20];           // are you sure that 20 chars will be enough?
cstring myWords[50];
char line[2048];                    // what's the max length of line?
std::cin.getline(line, 2048);
int i = 0;
char* nextWord = strtok(line, " trn");
while (nextWord != NULL)
{
    strcpy(myWords[i++], nextWord);
    nextWord = strtok(NULL, " trn");
}

但最好使用std::stringstd::getlinestd::istringstream>>运算符:

using namespace std;
vector<string> myWords;
string line;
if (getline(cin, line))
{
    istringstream is(line);
    string word;
    while (is >> word)
        myWords.push_back(word);
}
std::vector<std::string> strings;
for (int i = 0; i < MAX_STRINGS && !cin.eof(); i++) {
  std::string str;
  std::cin >> str;
  if (str.size())
    strings.push_back(str);
}