对于循环文件,数据正在重复并跳过其他行c++
for loop file data is repeating and skipping other lines c++
我几乎完成了读取联系人数据的程序,除了在读取时,某些行重复并跳过其他行。例如,这就是当前发生的情况:
Name: Herb SysAdmin
Address: 27 Technology Drive
Age: 27 Technology Drive
Phone: 25
Type: WORK
它重复地址,但跳过电话。下面的代码。
int EnterContact(string contacts, ListofContacts list)
// first number from the file depicting
{
// constant
ifstream inFile; //input file stream object
inFile.open("contacts.txt");
// variables
std:: string name,
address,
phone,
contactType;
string line;
int age;
int conNum = 0;
inFile >> conNum;
cout << endl;
cout << "There are " << conNum << " contacts in this phone." << endl;
for (int x = 0; x < conNum; x++)
{
getline(inFile, line);
getline(inFile, name);
getline(inFile, address);
inFile >> age >> phone >> contactType;
list[x] = Contact(name, address, age, phone, GetType(contactType));
}
//close the file
inFile.close();
return conNum;
}
如果有任何想法,或者我只是遗漏了一行代码,我们将不胜感激。
我的输入文件如下:
3
Herb SysAdmin
27 Technology Drive
25
850-555-1212
WORK
Sally Sallster
48 Friendly Street
22
850-555-8484
FRIEND
Brother Bob
191 Apple Mountain Road
30
850-555-2222
RELATIVE
此代码:
for (int x = 0; x < conNum; x++)
{
getline(inFile, line);
getline(inFile, name);
getline(inFile, address);
inFile >> age >> phone >> contactType;
list[x] = Contact(name, address, age, phone, GetType(contactType));
}
是错误的,因为您将格式化的输入与未格式化的输入混合在一起,而没有清除提取到conNum
和随后的contactType
后留下的换行符。
要修复它,请使用std::ws
:
getline(inFile >> std::ws, line);
// ^^^^^^^^^^^^^^^^^
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 结构和双指针隐藏在其他结构中,多层混淆
- UE4在OnComponentBeginOverlap上铸造其他actor
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 保留对其他类的成员函数的引用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 具有包含其他对象的类的对象创建顺序
- 让bool方法返回其他整数