2016-03-07 2 views
-1

Я пытаюсь использовать ПОЛУЧИТЬ линию для чтения «почтового код столбца целых чисел из .txt файла в этом формате:прочитать в колонке целых чисел из текстового файла C++

Name|Address|Zipcode|DateOfBirth

Это актуально часть того, что я до сих пор:.

std::ifstream testfile; 
testfile.open("data.txt"); 
string zipcode; 
std::vector<int> inputVec; 
while(!testfile.eof()) 
{ 
    std::getline(testfile, zipcode, '|'); 
    // Need to store all zipcodes as ints in an array or vector 
    // inputVec.push_back(zipcode); 
    // trying to cout to screen to make sure its the right col. 

    cout<<zipcode<<endl; // not working 
} 

Однако это читает весь файл, когда я просто хочу столбец почтового индекса

Как я о nly «захватить» этот столбец между '|' символами?

+0

Читать все столбцы, игнорировать те, что вам не нужно , Если ваши столбцы не имеют фиксированной ширины (что позволяет пропустить вперед 'n' байты), нет более эффективного способа. И, честно говоря, это не имеет значения. – DevSolar

+0

Пожалуйста, не предполагайте, что zip-коды всегда целые. В Великобритании это такие вещи, как «CB4 3PT». Учитывая, что вы не можете делать арифметические операции с zip-кодами, просто рассматривайте их как строки. –

+2

Почтовый индекс не должен быть целым, он должен быть строкой. zip-коды могут начинаться с '0', а целые числа не могут. – NathanOliver

ответ

0

Как я могу «захватить» эту колонку между '|' символы?

Текст записи в файле:

Name|Address|Zipcode|DateOfBirth 
    1  2  3 

Возможный подход (но захватить всю строку, а не только колонка)

int t394(void) 
{ 
    std::ifstream testfile; 
    testfile.open("data.txt"); 

    std::string aTxtRecord; 

    std::vector<std::string> inputVec; // tbd - or integer 

    do // read in whole file 
    { 
     // read entire line, one record at a time 
     std::getline(testfile, aTxtRecord); 

     if(testfile.eof()) break; // completed 

     // in the line, find one interesting '|', 
     // perhaps the first after zip, last in the line 
     size_t mrkr3 = aTxtRecord.rfind('|'); // last | 
     if(mrkr3 == std::string::npos) // not found 
     { 
     //handle bad record - no marker in the string 
     // set error code? std::cerr << from here? 
     break; // file invalid, maybe should quite 
     } 
     // mrkr3 now points at the marker behind the Zipcode 

     // find mrkr2 in front of the Zipcode 
     // use find 2 times? 
     // use rfind 1 more time? 
     size_t mrkr2 = 0; // tbd 

     // validate record - total mrkrs in line? 

     // compute length of zip string i.e. mrkr3 - mrkr2 - 1? 
     size_t length = mrkr3 - mrkr2; // ? -1 or -2 

     // now extract the Zipcode substring 
     // compute how many chars in zipcode field 
     std::string zipcode = aTxtRecord.substr(mrkr2+1, // char after mrkr2 
               length); 

     // store all zipcodes as strings (or tbd ints) in an array or vector 
     inputVec.push_back(zipcode); 

     // cout to screen for manual verification 
     std::cout << zipcode << std::endl; 

    } while(1); // only exit is error or eof() 

    testfile.close(); // possibly not needed 

    // sort the vector 

    return (0); 
} 
+0

Решите удалить это. Надеюсь, это не слишком «помощь». У меня больше. –

Смежные вопросы