文件处理 - 错误:与 while 循环 (C++) 中的"运算符>>"不匹配(代码::块)
file handling-the error: no match for 'operator>>' in while loop (c++)(code::block)
我编写了以下程序:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream theFile("students_info.txt");
cout<<"Enter the data as requested"<<endl;
cout<<"Press ctrl+z to exit"<<endl;
string name, address;
int contact[10];
while(cin >> name >> address >> contact) {
theFile << "nName: " << name
<< "n Address: " << address
<< "nContact: " << contact[10] << endl;
}
theFile.close();
return 0;
}
我从我的while循环条件中得到以下编译错误:
与"运算符>>不匹配
据我了解,我的条件意味着如果不按照这个进入 cin 的顺序,请离开循环!!
已编辑:解决了我的问题1:数组没有运算符>>。2:可以简单地使用整数类型3:如果不得不使用数组..需要一一放..
谢谢你帮助我
你的代码几乎没问题。这本来没关系:
while(cin >> name >> address) {
..
}
但是,operator >>
无法处理整数数组(int contact[10]
)!所以你必须逐个 int 读取它,例如:
while(cin >> name >> address >> contact[0] >> contact[1] >> ...) {
..
}
或将其替换为:
while(true) {
cin >> name;
if (!isValidName(name))
return; // or handle otherwise
cin >> address;
if (!isValidAddress(address))
return; // or handle otherwise
for (int i = 0; i < sizeof(contact)/sizeof(contact[0]); i++) {
cin >> contact[i];
if (!isValidContact(contact[i])
return; // or handle otherwise
}
}
请注意,我添加了输入验证。始终验证用户输入!
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 是否需要使用 - &gt;运算符在C 中调用成员函数时