2013-02-23 4 views
0

텍스트 파일의 내용을 2D 문자열 배열로 읽으려고 시도했으나 시도했거나 검색 한 내용과 상관없이 해결책을 찾을 수 없습니다. 이 코드는 가로 탭을 찾아 출력을 표시하여 텍스트 파일을 요소로 분리하여로드해야합니다. 있는 그대로 코드를 실행하면 온라인 검색에서 발견 된 오류가 발생합니다. 따라서 내가해서는 안되는 메모리를 조작하려고합니다. 필자는 코드 작성을 요구하지 않고 올바른 방향으로 밀어 넣을 것을 요구합니다. 미리 감사드립니다. getline을 사용하여 파일에서 2 차원 문자열 배열로 읽기

내가 프로그램을 실행할 때 내가 무엇을 얻을 수 있습니다 :

0x23fd5c 

Process returned -1073741819 (0xC0000005) execution time : 2.344 s 
Press any key to continue. 

편집 : 나는 코드를 수정 한 지금 기능이 정상적으로하지만 각 행의 마지막 항목에 저장되지 않도록 텍스트 파일을 올바르게. 어떻게 든 마지막 항목 인 숫자 100을 표시 할 수 있지만 그 위치를 전달하거나 playList [0] [5]를 표시하려고하면 다음 줄의 첫 번째 항목과 같습니다. 어떤 도움이 나는 아래의 현재 코드를 게시 놀라운 것입니다.

#include <iostream> 
#include <string> 
#include <iomanip> 
#include <cstdlib> 

using namespace std; 

void readTextFile(int &Count, string playList[50][5]); 
void userAddition(int &Count, string playList[50][5]); 




int main() 
{ 
string decision; 
string playList[50][5]; 
int Count = 0; 
readTextFile(Count, playList); 

cout << "If you would like to add to the list, Please enter 'Y'. If you would like to exit  
please enter 'N'. ----> "; 
getline(cin, decision); 
if (decision=="y" || decision=="Y") 
    userAddition(Count, playList); 
else 
{ 
    return(0); 
} 

return 0; 
} // End of Main FN. 






void readTextFile(int &Count, string playList[50][5]) 
{ 

string inputfield; 

ifstream infile("c:\\cTunes.txt", ifstream::in); 
    if (infile.is_open()) 
    { 
     // File is read. 
    } // end if 
    else 
    { 
     cout << "Error Opening file" << endl; 
     return; //Program Closes. 
    } // end else 

    cout << setw(30)<<left<< "TITLE"<< setw(10) <<left<<"LENGTH"<< 
     // Outputs a title to   each column that is displayed. 
    setw(40)<< left<<"ARTIST"<< setw(40) << left<<"ALBUM"<< 
    setw(15) << left <<"GENRE" << setw(5) << left << "RATING" << endl; 

getline(infile, inputfield, '\t'); // read until tab 
while(! infile.eof()) // loop until file is no longer valid. 
{ 

     playList[Count][0] = inputfield; 
     getline(infile, inputfield, '\t');   // read until tab. 

     playList[Count][1] = inputfield; 
     getline(infile, inputfield, '\t');    // read until tab. 

     playList[Count][2] = inputfield; 
     getline(infile, inputfield, '\t');   // read until tab. 

     playList[Count][3] = inputfield; 
     getline(infile, inputfield, '\t');   // read until tab. 

     playList[Count][4] = inputfield; 
     getline(infile, inputfield);    // read until end of line. 
     playList[Count][5] = inputfield; 

    cout << setw(30)<<left<< playList[Count][0] << setw(10) <<left<<playList[Count][1] <<   
    // Output the line number equal to count. 
    setw(40)<< left<<playList[Count][2] << setw(40) << left<< playList[Count][3] << 
    setw(15) << left << playList[Count][4] << setw(5) << left << playList[Count][5] <<      
    endl; 

    /*cout <<"Title: " << setw(25)<<left<< playList[Count][0]<<endl; 
    cout <<"Length: " << setw(5) <<left<<playList[Count][1] << endl; 
    cout <<"Artist: " << setw(50)<< left<<playList[Count][2] << endl; 
    cout <<"Album: " << setw(40) << left<< playList[Count][3] << endl; 
    cout <<"Genre: " << setw(15) << left << playList[Count][4] << endl; 
    cout <<"Rating: " << setw(5) << left << playList[Count][5] << endl<<endl;*/ 

    Count++;   // Increment counter by 1 
    getline(infile, inputfield, '\t'); // read next line until tab. 

    } // end while 
infile.close(); // close the file being read from. 
cout<<endl<<endl<<playList[0][5]<<endl; 
} // End of readTextFile 

내가 줄의 끝까지 읽기하지만 난 손실에 진정으로있을 때의 getline 문제를 일으키는 생각 :

여기 내 코드입니다.

+1

'string playList [19] [5]; '왜?! 왜 '벡터 <벡터 >'을 사용하지 않겠습니까? – us2012

+0

예제 입력 + 예상 출력을 첨부하면 특정 상황에 더 적합한 대답을 얻을 수 있습니다. – LihO

+0

또한 파일을 여는 동안 오류가 발생했을 때 :'else {cout << "Error Error opening file"<< endl; }'나머지는 당신의 함수가 실행되는 것을 막기 위해'return'을 사용해야합니다. – LihO

답변

0

먼저, 다음 줄에 그주의 : 당신이 배열이 아닌 내용의 주소를 인쇄하는

cout << playList << endl; 

. 내용을 인쇄하려면 루프가 필요합니다.

둘째, 다음 코드 :

if (infile.is_open()) 
{ 
    // ok, read in the file 
} // end if 
else 
{ 
cout << "Error Opening file" << endl; 
//a return statement is missing 
} 

당신은

마지막으로, 함수가 아무것도 반환하지 않습니다 (충돌을 일으킬 수) 폐쇄 스트림에서 읽기 피하기 위해 return 문이 필요합니다 따라서 void 으로 선언되거나 문맥에 따라 의미가없는 값을 반환해야합니다.

희망과 행운을 빕니다!

+0

도움을 주셔서 감사합니다. 주소를 인쇄하면 위에 게시 한 오류가 표시됩니까? 내가 코드를 실행할 때 윈도우즈는 컴파일러가 아닌 프로그램을 닫으라는 메시지를 표시합니다. 그래서 필자는 내가해서는 안되는 무언가에 접근하는 것을 믿습니다. 함수를 void로 바꾸고 오류 검사에 반환을 추가했습니다. –

+0

코드를 수정하기 전에 심지어 코드를 컴파일 할 때 코드가 잘 작동했기 때문에 말하기 어렵습니다. 비주얼 스튜디오 을 사용하고 있습니까? –

+0

나는 Visual Studio와 CodeBlocks를 모두 시험해 봤지만 :-(나는 6 시간 동안 작동하도록 노력했다. 나의 유일한 다른 생각은 내 컴퓨터가 컴파일러가 파일에 접근하는 것을 허용하지 않는다는 것이다. –

0
당신은 말 ... 정말 대신 배열의 std::vector의를 사용해야 읽기 위해, std::getline 파일에서 읽기위한 문자열, std::ifstream를 저장 std::string를 사용하는

:

typedef std::vector<std::string> Line; 
std::vector<Line> playList; 

그것은을 위해 일을 더 쉽게 만들 것 당신. 는 또한 당신이 당신이 파일에서 읽는 방법을 변경하는 것이 좋습니다 :

while(getline(...)) 
{ 
    ... 
} 

하지만이 std::vector를 사용하는 것이 허용되지 않기 때문에, 함수는 다음과 같이 수 :

// reads the content of input file and stores it into playList: 
void readTextFile(std::ifstream& infile, std::string playList[][5]) 
{ 
    std::string line; 
    for (int lineIndex = 0; getline(infile, line); ++lineIndex) 
    { 
     // skip empty lines: 
     if (line.empty()) continue; 

     std::string word; 
     std::istringstream lineStream(line); 
     for (int wordIndex = 0; getline(lineStream, word, '\t'); ++wordIndex) 
     { 
      // skip empty words: 
      if (line.empty()) continue; 

      playList[lineIndex][wordIndex] = word; 
     } 
    } 
} 

이것은 다음과 같이 사용할 수 있습니다 :

std::string playList[19][5]; 

std::ifstream infile("c:\\Test.txt"); 
if (infile.is_open()) 
{ 
    readTextFile(infile, playList); 
    infile.close(); 
} 
else 
    std::cout << "Error Opening file" << std::endl; 

cout << playList << endl;은 첫 번째 단어의 주소를 출력합니다. 모든 단어를 인쇄하려면 루프를 작성해야합니다.

+0

빠른 응답을 보내 주셔서 감사합니다! 저는 현재 매우 기본적인 C++ 프로그래밍 클래스에 있으며 벡터를 아직 다루지 않았기 때문에 불행히도 사용할 수 없다고 생각합니다. –

+0

@Davidtftyfy : 지금 내 대답을 확인하십시오. 주어진 해결책은 파일의 각 줄에 5 단어를 초과하지 않는다는 사실에 의존합니다. – LihO

+0

좋아, 나는 그것을 시도 할 것이다. 당신이 그 시간을 가져 주셔서 감사합니다. 나는이 사이트에 얼마나 도움이되는 사람들이 있는지 놀라는데, 이것은 내 첫 번째 게시물이기 때문에 무엇을 기대해야할지 몰랐다. –

0

readTextFile 함수는 아무 것도 반환하지 않습니다. 문자열을 반환해야합니다. 오류 what(): basic_string::_S_construct null not valid이 발생하면 문제가 발생합니다. -Wall 컴파일러 옵션을 사용하면 비슷한 문제를 피할 수 있습니다.