여기에 초보자를 코딩합니다. C++가 제 첫 번째 언어입니다. 가능한 경우 설명을 적어주십시오.파일에서 읽기 C++ (Line by line - mixed variables)
나는 혼합 변수를 포함하는 파일에서 행을 읽어야한다. 저는 현재 2 가지 문제에 직면하고 있습니다 :
모든 문장을 읽을 수 있도록 입력 문을 루핑합니다. 나는 루프 수행하려면 다음 코드를 사용하여 제한하고 있습니다 :
while(inputFile.peek() != EOF)
나는이 다음에 문자를 확인해야하고 EndOfFile 경우는 루프를 중단 할 것을 이해 할을하지만 난 그것을 얻을 수 없다 일하다.
bool (공백 제외)이 앞에 오는 문자열 읽기. 공백을 건너 뛰려면 내가 사용 하죠 :
Car CN 819481 maintenance false NONE Car SLSF 46871 business true Memphis Car AOK 156 tender true McAlester
내 코드는 다음과 같습니다 : 다음과 같이
while(inputFile.peek() == ' ') inputFile.get();
파일의 내용은 다음과 같습니다. 나는 그것이 input()
일 경우에만 main()
기능을 생략했습니다.
#include <iostream> //used in main()
#include <iomanip>
#include <string>
#include <fstream> //to work with file
#include <cstdlib> //for exit() function
using namespace std;
void input(){
ifstream inputFile;
string type, rMark, kind, destination;
int cNumber;
bool loaded;
inputFile.open("C:\\My Folder\\myFile.txt"); //open file
if (!inputFile){
cerr << "File failed to open.\n";
exit(1);
}
//read file contents
while(inputFile.peek() != EOF){
//initially I had >>destination in the statement below as well
//but that gave me the same results.
inputFile >> type >> rMark >> cNumber >> kind >> loaded;
//skip whitespace
while(inputFile.peek() == ' '){
inputFile.get();
}
//get final string
getline(inputFile, destination);
cout << type << " " << rMark << " " << cNumber << " " << kind << " ";
cout << boolalpha << loaded << " " << destination << endl;
}
inputFile.close(); //close file
} //end input()
프로그램을 실행 한 후 내가 얻을 :
Car CN 819481 maintenance false
그래서 첫 번째 라인은 부울 값까지 읽어됩니다 (마지막 문자열은 생략됩니다), 루프는 작업 (또는하지 않습니다 그러나 그것은해서는 안되는 것을 읽는 것입니까?). 나는 .peek() 및 .gets() 주위를 움직이려고 시도했지만 어떤 조합도 효과가 없다.
미리 감사드립니다. 'C++는'0 '을보고 기대 또는'1 '이 아닌, 부울 변수를 읽고
inputFile >> type >> rMark >> cNumber >> kind >> boolalpha >> loaded;
그렇지 않으면 :
감사합니다. 지금 작동하십시오 :) – gboyn
작동하는 경우, 응답을 upvote 받아 받아 들여야합니다. – user31264
수락 방법 -이 웹 사이트의 신규 여부. 편집 : 발견 – gboyn