使用getline从文件读取时的垃圾值

时间:2015-11-05 11:33:00

标签: c++ getline

我正在编写一个小程序,只是从特定格式的srt文件中获取行。但是我在使用getline的第一个(也是唯一的)读取中获得了垃圾值。有人能指出我为什么会出现这种异常行为?

//Small program to get the text from the srt files.

#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<vector>
#include<sstream>
#include<conio.h>

using namespace std;

void srtToTranscript(ifstream* iFile, ofstream *oFile);

int main(){
std::string file_name;
std::string transcript;

cout << "Enter srt file name (without extension)";
cin >> file_name;

ifstream iFile;
ofstream oFile;

iFile.clear();

iFile.open("data\\" + file_name+".srt");
oFile.open("data\\" + file_name + "_result.txt");
srtToTranscript(&iFile,&oFile);
cout << "Conversion done. Check in the same folder";
cout << "Press a key to exit... ";
while (!_kbhit());
char dummy = _getch();
return 0;
}

void srtToTranscript(ifstream* iFile, ofstream* oFile)
{
        int i = 1;
        std:string line;
        for (; getline(*iFile, line);)  
        {
            cout << line << endl;
            cout << to_string(i) << endl;

            if (line.compare(to_string(i)) == 0){
                getline(*iFile, line);
                i++;
                continue;
            }

            *oFile << line + ",\n";
        }
        oFile->close();
}
附加的是我正在阅读的文件的示例:

  

1

     <00> 00:00:00,000 - &gt; 00:00:12000

     译者:Thu-Huong Ha

     

2

     <00> 00:00:12,038 - &gt; 00:00:15012

     

过去二十年来,印度已成为

1 个答案:

答案 0 :(得分:0)

问题是您的ifile未成功打开。

我在您的包含列表中看到#include <conio.h>,所以我假设您正在使用Visual Studio?如果在设置Visual Studio时使用了默认目录结构,则说你有一个名为的项目:&#34; Foo&#34;你的.srt文件需要在这里:

  

... / Documents / Visual Studio 20 ## / Projects / Foo / Foo / data / Foo.srt

当我正确地将文件放在那里并在我输入的提示时:

  

我得到了这个输出:&#34; ... / Documents / Visual Studio 20 ## / Projects / Foo / Foo / data / Foo_result.txt&#34;:

  <00> 00:00:00,000 - &gt; 00:00:12,000
  ,
  译者:Thu-Huong Ha,
  ,
  00:00:12,038 - &gt; 00:00:15012,
  ,
  在过去的二十年里,印度已成为,

我确定的一件事是line中的srtToTranscript声明已定义:

string line

std:string line
相关问题