【问题标题】:Reading from text file with ifstream使用 ifstream 从文本文件中读取
【发布时间】:2015-12-30 07:02:20
【问题描述】:

所以我正在尝试从文本文件中读取。它表明我可以成功地从文件中读取但是当我尝试计算这些值时,它只显示 0,而我在文本文件中有其他值。

#include <iostream>
#include <fstream>
#include <string>


using namespace std;

int main()
{

    std::ifstream file("numbers.txt");
if (file) {
    cout << "Managed to read file successfully. \n";
}else{
    cout << "Unable to read file.";
}


int x, y;

file >> x >> y;

cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;

    return 0;
}

【问题讨论】:

标签: c++ file output fstream


【解决方案1】:

带有 numbers.txt 文件

45
15

使用 gcc 查找您的代码。

int main()
{
     std::ifstream file("numbers.txt");
     if (file) 
     {
        cout << "Managed to read file successfully. \n";
        int x, y;
        file >> x >> y;

        cout << "Num 1: " << x << endl;
        cout << "Num 2: " << y << endl;
    }
    else
    {
        cout << "Unable to read file.";
    }
    return 0;
}

【讨论】:

  • 这不是一个答案,它不能解释他的程序出了什么问题或者你是如何修复它的。应该是评论。当您获得声望 = 50 时,您将能够评论其他人的问题。
【解决方案2】:

上面的代码会打印你的操作状态,如果你想读取和显示内容,你必须这样编写代码:

#include<iostream>
#include<fstream>

using namespace std;         

int main()    
{
            ifstream stream1("D:\\file1.txt");    
            char a[80];

            if(!stream1)    
            {
                        cout << "While opening a file an error is encountered" << endl;    
            }    
            else    
            {    
                        cout << "File is successfully opened" << endl;    
            }

            while(!stream1.eof())    
            {    
                        stream1 >> a;    
                        cout << a << endl;    
            }

            return(0);    
}
猜你喜欢
  • 2011-12-28
  • 2010-12-09
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2020-07-04
相关资源
最近更新 更多