简体   繁体   English

如何从C ++中的txt文件输出。 该文件有一两行

[英]How to output from a txt file in C++. The file has one two rows

The rows are as in the example: 这些行如示例中所示:

583-4-153-15601-4  '\t' Time Warp Trio  '\t'  Scieszka Jon    '\t' 50  '\t'  50
583-0-133-15601-2  '\t'  Djemte e rruges pal    '\t'    Ardit Zotaj '\t' 50  '\t'  50

So Every string is separated by a tab. 因此,每个字符串都由一个制表符分隔。 Basically it contains the information for a book. 基本上,它包含一本书的信息。

ISBN-TITLE-AUTHOR-PRICE-NO. OF COPIES.<
//583-4-153-15601-4  '\t' Time Warp Trio  '\t'  Scieszka Jon    '\t' 50  '\t'  50
//583-0-133-15601-2  '\t'  Djemte e rruges pal    '\t'  Ardit Zotaj '\t' 50  '\t'  50

I have done this work so far but it doesn't give the right output me in the cmd. 到目前为止,我已经完成了这项工作,但是在cmd中没有正确输出。

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{ 
    ifstream fin;
    fin.open("bookdata.txt");
    string line;
    string isbn, title, author;
    int var1 = 0;
    int var2 = 2;

    while (!fin.eof())
    {
        getline(fin, isbn, '\t');
        getline(fin, title, '\t');
        getline(fin, author, '\t');
        fin >> var1;
        fin >> var2;
    }

    cout << isbn << title << author << endl;
    fin.close();
    cout << var1 << var2 << endl;
}

Try something like this (not tested): 尝试这样的事情(未经测试):

while (getline(fin, isbn, '\t') && getline(fin, title, '\t') &&
       getline(fin, author, '\t') && fin >> var1 && fin >> var2 &&
       fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'))
{
    cout << isbn << title << author << " " << var1 << " " << var2 << endl;
}

I used fin.ignore , so that we don't get \\n , which is still in the stream after fin >> var2 , as the first character of the next isbn . 我使用fin.ignore ,这样我们就不会得到\\n (它在fin >> var2之后仍在流中)作为下一个isbn的第一个字符。 It could be also fin.ignore(1, '\\n') ... 也可能是fin.ignore(1, '\\n') ...

You also have to print these variables in the loop, otherwise you'll just print the information of the last row in the file. 您还必须在循环中打印这些变量,否则,您将只打印文件中最后一行的信息。

I also noticed, that you have string line; 我还注意到,您有string line; lying around. 躺在周围。 Another approach, now utilizing this object can be found here . 现在可以在这里找到利用该对象的另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM