C++,如何获得多个输入除以空白
C++, How to get multiple input divided by whitespace?
我有一个程序需要获取多个cstring。我现在一次输入一个,然后问你是否想输入另一个单词。我找不到任何简单的方法来只获得一个单词被划分为空白的输入。即"一二三",并将输入保存在cstrings数组中。
typedef char cstring[20]; cstring myWords[50];
目前,我正在尝试使用getline并将输入保存到cstring中,然后我尝试使用string.h库来操作它。这是正确的方法吗?否则怎么办?
如果您真的必须使用c样式字符串,您可以使用istream::getline
、strtok
和strcpy
函数:
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::string
、std::getline
、std::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);
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 无法通过空白将文本文件行分隔为矢量
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 检测整数类型变量上的空白输入
- 输入层类型:图像数据在窗口咖啡cpp中给出空白输出
- 为什么从文件输入中读取 std::string 会返回空白
- C++,如何获得多个输入除以空白
- 如何使用getline()避免空白输入
- 如何使用空白作为分隔符对字符串进行标记并将标记输入到列表中