나는이 문제에 대해 이미 여러 번 검색했습니다. 프로그래밍으로 돌아가고 있으며 시작하기 위해 간단한 코드를 작성하려고합니다.ifstream을 사용하여 입력 파일에서 데이터를 올바르게 읽으려면 어떻게해야합니까?
현재 g ++을 사용하여 파일을 컴파일하고 있습니다. 나는 내 코드와 입력 파일을 입력하기 위해 gedit을 사용하고있다.
기본적으로 입력 파일 (별도의 정수 목록)에서 데이터를 읽고 텍스트 파일에있는 정수의 총 개수를 찾고 배열에 저장하고 싶습니다.
다음은 내 메인 파일에 사용되는 헤더 파일 입니다.
//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;
}
입력 파일 내가 생각하는 문제는 라인
inputfile >> n;
에게 있습니다 1
2
5
9
0
이것은 다른 사람들에게 주어진 해결책이었습니다. 그리고 이것은 제가 수업에서 사용했던 것입니다. 그러나 어떤 이유로 텍스트 파일이 올바르게 읽혀지지 않아 뭔가 잘못하고있을 것입니다. 나는 다음을 사용하는 경우
, 내 코드를 테스트하기 위해 cout을 문을 설정하고 이것은 당신이 단지 1 항목을 계산 한 후 내가 확인할 때 볼 수 있듯이 내가
[email protected]:~/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");
^
[email protected]:~/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
을 가지고 무엇을 배열에 저장된 숫자를 보려면 을 텍스트 파일의 두 번째 숫자로 저장합니다. 첫 번째 항목을 완전히 건너 뛰었습니다.
하는 경우 당신이 궁금해, 실제 out_2.txt 파일 나는 또한 라인
while(!inputfile.eof())
{
inputfile >> n;
//std::cout << std::setw(10) << n;
}
을 시도하지만 9 항목을 계산 곳이 단지 다른 문제를 제기
There are (1) numbers in the input file
있다 합계 및 배열에 저장된 숫자는 올바르지 않은 큰 정수입니다.
도움을 주시면 감사하겠습니다. 감사합니다
당신은 ** 항상 ** 당신의 읽기가 성공했는지를 시험해야합니다 ** 읽기를 시도한 후에 ** 시도하십시오! 'eof()'를 사용하는 것은 일반적으로 잘못된 것이다. 파일의 끝에 도달했거나 다른 이유로 오류를보고하기 전에 읽기가 실패했는지 여부를 판별하는 것이 대부분 유용합니다. 스트림을 'bool'(예 :'while (input >> n) {...} ')으로 변환하면됩니다. –
이 태그가 objective-c 인 이유는 무엇입니까? – Borgleader