【发布时间】:2016-06-12 01:05:55
【问题描述】:
我已经对此问题进行了多次搜索。我刚刚回到编程,我正在尝试创建一个简单的代码来开始。
我目前正在使用 g++ 来编译我的文件。我正在使用 gedit 键入我的代码和输入文件。
基本上我想从我的输入文件(单独整数列表)中读取数据,找到文本文件中整数的总数,然后将它们保存到一个数组中。
以下是我的主文件中要使用的HEADER文件。
//Make program to read data from in_2.txt then add them and print to output file out_2.txt
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include <iomanip>
std::ofstream outputfile("out_2.txt", std::ios::out);
class TEST_ADD{
public:
TEST_ADD(void); //constructor. Will use an unknown input file so nothing to do
void INPUTREAD(char *); // Read the data from the input file. Ex. //b.INPUTREAD ("in.2")
void ADD(void); //Will perform the actual summation and store value into int add
void PRINT(void); // Print the numbers being summed, along with it's sum into out.2
private:
int add; //will store the sum of the numbers
int n; //will keep track of total number of entries
int A[20]; //used to store the number from the input file into an array
};
TEST_ADD::TEST_ADD (void)
{
n=0;
}
void TEST_ADD::INPUTREAD (char * in_name) //will record the users input file (written in main.cpp)
//and store it as in_name
{
int i;
std::ifstream inputfile(in_name, std::ios::in);
std::cout << "Number of n before input file read : "<< n << std::endl;
inputfile >> n;
/*while(!inputfile.eof())
{
inputfile >> n;
//std::cout << std::setw(10) << n;
}*/
std::cout << "Number of n after input file read : " << n << std::endl;
std::cout << "There are ("<< n << ") numbers in the input file" << std::endl; //check
for(i=0;i<n;i++)
{
inputfile >> A[i];
std::cout << "A[" << i << "] = " << A[i]<< std::endl;
}
outputfile << "There are ("<< n << ") numbers in the input file" << std::endl;
}
主文件
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include "Project2.h"
int main()
{
TEST_ADD b;
b.INPUTREAD("in_2.txt");
return 0;
}
输入文件
1
2
5
9
我认为是线的问题
inputfile >> n;
这是给其他人的解决方案,这是我以前在课堂上使用的,但由于某种原因,文本文件没有被正确读取,所以我一定做错了。
当我使用以下内容时,我设置了一个 cout 语句来测试我的代码,这就是我得到的
jason@jason-Satellite-S55-B:~/C++/Second_program$ g++ main2.cpp -o project2
main2.cpp: In function ‘int main()’:
main2.cpp:10:24: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
b.INPUTREAD("in_2.txt");
^
jason@jason-Satellite-S55-B:~/C++/Second_program$ ./project2
Number of n before input file read : 0
Number of n after input file read : 1
There are (1) numbers in the input file
A[0] = 2
如您所见,它只计算 1 条目,然后当我检查它存储在数组中的数字时,它存储 2 这是第二个数字在文本文件中。它只是完全跳过了第一个条目。
如果您想知道,实际的 out_2.txt 文件有
There are (1) numbers in the input file
我也试过这条线
while(!inputfile.eof())
{
inputfile >> n;
//std::cout << std::setw(10) << n;
}
但这只是带来了其他问题,它总共计算了 9 个条目,并且存储在数组中的数字是不正确的大整数。
感谢任何帮助。谢谢
【问题讨论】:
-
您应该始终测试您的阅读是否成功尝试阅读!使用
eof()通常是错误的。在报告错误之前,确定读取失败是因为到达文件末尾还是其他原因通常很有用。只需将流转换为bool,例如while (input >> n) { ... }。 -
为什么这被标记为objective-c?
标签: c++ objective-c class ifstream readfile