读取txt文件显示异常

时间:2015-05-07 20:47:06

标签: c++ getline

我在下面写了一些代码。titleauthors的类型是char数组,我无法更改它。当数据从键盘输入时,结果是正常的。

void BookException::getBook()
{
    cout<<"Id number: ";
    cin>>booknum;
    cout<<"Title: ";
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.getline(title, sizeof(title), '\n');
    cout<<"Authors: ";
    cin.getline(authors, sizeof(authors), '\n');
    cout<<"Number of pages:";
    cin>>pagenum;
    cout<<"Price: ";
    cin>>price;
    cout<<"over"<<endl;
}

以下是

下面的输入文字
1
How to program C++
Paul Deitel, Harvey Deitel
1028
112.83

但是当我尝试从txt文件中读取一些文本时,它会像这样显示:

Id number: Title: Authors: Number of pages:Price: The no. 0 book error. Title: Authors: Number of pages: 0 Price: 0.00 Incorrect price. 我认为getline由于问题但我不知道如何解决它。谢谢。

1 个答案:

答案 0 :(得分:1)

我没有看到您的代码中传入或打开了文件。在阅读或换行后,您也永远不会打印任何变量。使用字符串会容易得多,但是如果你必须使用char数组,我建议编写一个函数来从c-string转换为字符串并返回,请参阅:c_str()

@BeforeClass
public static void beforeClassMethod()
{
  System.out.println("BeforeClass assume");
  Assume.assumeTrue(false);
  System.out.println("AfterClass assume");
}
@Before
public void beforeMethod()
{
  System.out.println("Before");
}
@Test
public void testMethod()
{
  System.out.println("Test");
}
@After
public void afterMethod()
{
  System.out.println("After");
}
@AfterClass
public static void afterClassMethod()
{
  System.out.println("AfterClass");
}


Output:

BeforeClass assume
AfterClass

我建议您阅读此内容,除非您理解这一切:input/output with files

void BookException::getBook() { string booknum, title, authors, pagenum, price; ifstream fin; //file in fin.open("book.txt"); //Open the file getline(fin, booknum); //Read line from file first cout << "Id number: " << booknum << endl; //Then print getline(fin, title); cout << "Title: " << title << endl; getline(fin, authors); cout << "Authors: " << authors << endl; getline(fin, pagenum); cout << "Number of pages:" << pagenum << endl; getline(fin, price); cout << "Price: " << price << endl; cout << "over" << endl; fin.close(); //Close the file } 用法可以找到here