C++ 带文件的输入/输出

标签 c++ file-io

#include <iostream>
#include <fstream>

using namespace std;


int main()

{
    int a , b , c , d; 
    ifstream myfile;

    myfile.open ("numbers.txt");
    myfile >> a, b, c;
    d = a + b + c;

    ofstream myfile;
    myfile.open ("result.txt");
    myfile << d;
    myfile.close();

    return 0
}

number.txt 文件包含 3 个数字 10 , 8 , 9 。我试图让程序读取它们并将它们汇总到 results.txt 中。

我得到的错误是:

conflicting declaration 'std :: ifstream myfile'
no match for 'operator << in myfile << d'
'myfile' has a previous declaration as 'std :: ifstream myfile' 

最佳答案

(这只解决了您代码中的两个错误之一。)

myfile >> a, b, c;

此行不会读取所有三个变量 abc 的输入。它只读取 a 的输入,然后计算 b 并丢弃该值,然后计算 c 并丢弃该值。

你想要的是:

myfile >> a >> b >> c;

这将从 myfile 中读取所有三个变量的值。

关于C++ 带文件的输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501331/

相关文章:

c++ - 如何将字符串流中的数据写入文件(CPP)

php - MySQL 连接速度与 PHP 文件访问速度

Java重复将 double 写入txt文件

c - 如何从文本文件中读取多个数字

java - 创建新目录

c++ - 在 linux ubuntu 12.04 中编译 srilm 时出错

c++ - 将 std::string::length 转换为 int

c++ - std::is_same 等同于非专用模板类型

c++ - 一个参数中有 2 个常量