尝试在 getline 中使用 int
Trying to use int in getline
cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
getline(cin, totalquestions);
这一小段代码来自我创建的类中的一个函数,我需要totalquestions
成为一个 int,以便它可以运行一个 for 循环并继续询问我提出的问题总数。
question q;
for(int i = 0; i < totalquestions; i++)
{
q.inputdata();
questions.push_back(q);
}
这段代码在哪里发挥作用? 有人有任何想法来做这项工作吗?
使用
cin >> totalquestions;
也检查错误
if (!(cin >> totalquestions))
{
// handle error
}
getline
将整行读取为字符串。 你仍然会有要将其转换为 int:
std::string line;
if ( !std::getline( std::cin, line ) ) {
// Error reading number of questions...
}
std::istringstream tmp( line );
tmp >> totalquestions >> std::ws;
if ( !tmp ) {
// Error: input not an int...
} else if ( tmp.get() != EOF ) {
// Error: unexpected garbage at end of line...
}
请注意,只需将std::cin
直接输入到 totalquestions
不起作用;它将留下尾随 缓冲区中的'n'
字符,这将取消同步所有以下输入。 可以通过添加调用std::cin.ignore
,但这仍然会错过错误由于尾随垃圾。 如果你正在做面向线的输入,坚持使用getline
,并使用std::istringstream
进行任何必要的转换。
这样做:
int totalquestions;
cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
cin >> totalquestions;
Getline是为了抢chars
。它可以用getline()
来完成,但cin
要容易得多。
从用户那里获取 int 的更好方法之一:-
#include<iostream>
#include<sstream>
int main(){
std::stringstream ss;
ss.clear();
ss.str("");
std::string input = "";
int n;
while (true){
if (!getline(cin, input))
return -1;
ss.str(input);
if (ss >> n)
break;
std::cout << "Invalid number, please try again" << std::endl;
ss.clear();
ss.str("");
input.clear();
}
为什么它比使用 cin>> n 更好?
实际文章解释原因
至于你的问题,使用上面的代码获取int值,然后在循环中使用它。
不要使用 getline
:
int totalquestions;
cin >> totalquestions;
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- Seg Fault Issue C++ (file IO / getline)
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 将 int 与字符串和 getline 一起使用,没有错误
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- 当将 getline 与 int 一起使用时,如何修复"没有重载函数 'getline' 的实例与参数列表匹配"
- Cin.Getline(char,int)在循环中被跳过
- 用getline在字符串中从文件中读取,然后将数字从int数组中的字符串划分
- 接收错误"no matching function for call to 'getline(std::ifstream&, int&, char)'"
- 将getline()字符串拆分为多个int和char变量
- 类和 int 的 getline 等效,也'no viable overloaded ='错误
- 尝试在 getline 中使用 int