如何通过cin为2个以上的变量输入流
How to input stream by cin for more than 2 variable
我对C++流有问题。我需要输入一些数字,程序应该比较"字符串"并标记为"const"grove"等。主要问题是当我不知道有多少用户想要输入时,如何输入这些数字。我认为最好的想法是使用-1作为结束的最后一个"标识符"。但是如何一个接一个地输入这些数字(digital1[space]digital2[space]Digital3[space]-1)?我试着做
int main() {
int repeatCount = 0;
int stringCount = 0;
float digit1 = 0;
float digit2 = 0;
cout << "How many strings You have?" << endl;
cin >> iloscPowtorzen;
while(stringCount != repeatCount)
{
cin >> digit2 >> digit2;
while (digit2 != -1)
{
//HERE I HAVEN'T GOT ANY IDEA
}
stringCount++;
}
system("pause");
return 0;
}
示例(应该如何工作):
输入
<<How many strings You have?
>>3
>>1 1 1 1 -1
>>1 2 3 4 -1
>>4 3 2 1 -1
输出
<<const
<<grove
<<decrease
对不起我的英语。问候
一次读取一个,而不是成对读取。否则,它将把下一行的第一个数字读入第二个变量。
for (stringCount = 0; stringCount < repeatCount; stringCount++) {
while (true) {
cin >> digit2;
if (digit2 == -1) {
break; // get out of while loop
}
cin >> digit1;
// do stuff with digit1 and digit2
}
}
试试这个:
while (true)
{
float curNum;
cin >> curNum;
if (!cin)
break;
// do your logic here
}
我脑海中第一件事:
- 将整行作为字符串读取
- 使用带空格的
strtok
作为分隔符 strtok
将以字符串形式返回每个数字,每次输入时调用atoi
这可能不是最优雅的解决方案,但它很有效,您不需要在最后输入"-1"或任何内容。只需输入空格分隔的数字,点击回车键即可完成(直观的输入方式)。
相关文章:
- 堆栈中大小变量输入错误 (C++)
- 如何忽略输入流中的某些字符?
- C++输入流.与 cin unget() 函数有点混淆
- 从输入流中读取行,并能够跳过块
- 使用 Visual Studio 代码读取 C++ 中的输入流时出错
- 处理输入流运算符>>中的无效输入
- 如何在C++中从标准输入中获取变量输入
- 树莓派上的端口音频,找不到输入流的设备
- 如何将C++输入流分隔符包含在结果令牌中
- 如果两个输入流相等,我如何构造主()到输出是
- 使用非成员函数从输入流中提取类对象
- 用户无法为第二个变量输入。C++
- CIN是否将输入流中的无效字符取用
- 动态内存分配和输入(流)运算符C++
- 计算输入流中值的出现次数
- (C++) 学习向量 - 编码/输入流终止/比较向量的问题
- 如何通过cin为2个以上的变量输入流
- 输入流失败后对输入变量的影响
- 通过输入流获取输入并将其存储在结构变量中
- 如何处理csv文件输入流,我需要将文件的每一行中的数据划分为6个不同的变量(类型字符串和int)