【问题标题】:C++ can't read from file properlyC++ 无法正确读取文件
【发布时间】:2019-03-30 07:37:06
【问题描述】:

为什么 C++ 不能正确读取文本?即使我输入下图中显示的名称之一,它也会写入“错误名称”。看下面的截图

#include <iostream>
#include <fstream>
using namespace std;

int main(){
ifstream data_base;
data_base.open("database.txt", ios::out);

string name, a;
int b, c, d, e, test=0;

system ("cls");
cout<<"enter name "<<endl;
cin>>name;

while (data_base >> a >> b >> c >> d >> e){
    if (name == a) test=1;
}

if (test!=1)
cout<<"wrong name"<<endl;

return 0;
}

【问题讨论】:

  • “没有正确阅读文本”是什么意思?你输入了什么,你期望发生什么以及实际发生了什么?另外,请将您的代码粘贴到问题中,而不是发布图片链接。
  • 请编辑您的问题以包含minimal reproducible example。请注意,您的代码应该以文本形式发布,没有人会将图像转换为文本来检查您的程序,并且编译器不接受图像。
  • 请不要张贴代码和输入输出的图片。将其发布为 text in 问题。
  • 您有足够的声望来复制您的文本并将其粘贴到问题中。每个人都这样做。
  • if (str == ..) 肯定失败

标签: c++ windows c++11 visual-c++ c++14


【解决方案1】:

尝试以下方法:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream data_base;
    data_base.open("database.txt", ios::out);

    string name, a;
    int b, c, d, e, test = 0;

    system ("cls");
    cout << "enter name ";
    cin >> name;

    while (data_base >> a >> b >> c >> d >> e)
    {
        if (name == a)
        {
            test = 1;
            break;
        }
    }

    if (test!=1)
        cout << "wrong name" << endl;
    return 0;
}

让我知道它是否有效。

【讨论】:

  • 即使我找到正确的名称,程序也无法识别它......仍然得到“错误的名称”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
  • 2020-03-11
相关资源
最近更新 更多