我想制作两个文件,一个命名输入,另一个命名输出

在输入文件中,我有:Lorem ipsum dolor坐在amet,安全adipiscing精英。 Vestibulum dignissim,个人简历。 Sed,结果。

对于字符串数组,应为128个元素。

我想做的是使程序从输入文件中逐字读取到128个元素的字符串数组中。

这是到目前为止我想出的代码:

int main(){
string Lnm[128];
int l = 0;
//input file and output file.
fstream theInput("Input.txt", ios::in);
fstream theOutput("Output.txt", ios::out);

//checks if file is there
if (!theInput.good()){
    cout << "A PROBLEM HAS OCCURED!\n" << "______________________________\n" << "ERROR: File does not exist! Please make a valid file.\n";
    system("pause");
    return 0;
}

for (Lnm; getline(theInput, Lnm[l], '\n');) {
    cout << Lnm << endl;
}

//checking

if (theInput.eof()){
    cout << "Successful!\n";
    theOutput << Lnm[l] << "\n";

}
else if (theInput.fail()){
    cout << "Invalid Input\n";
}
else if (theInput.bad()){
    cout << "Error! go and fix the problem.\n";
}
theInput.close();
theOutput.close();

system("pause");
return 0;


}

我的问题是我正在到达事物的存储位置,或者至少是我认为的那样。我将如何使其显示文本并将其导入到输出中?

最佳答案

这些线

for (Lnm; getline(theInput, Lnm[l], '\n');) {
    cout << Lnm << endl;
}


不要增加l。由于Lnm[0]被初始化为l,因此最终只能将单词读入0

同样,cout << Lnm << endl;可能只打印一个指针-指向Lnm第一个元素的指针。

将它们更改为:

for ( l = 0; getline(theInput, Lnm[l], '\n'); ++l ) {
    cout << Lnm[l] << endl;
}


准备将字符串打印到输出文件时,需要使用:

for ( int i = 0; i < l; ++i ) {
   theOutput << Lnm[i] << "\n";
}


PS我将使用numLines而不是l。这将使代码更具可读性。

10-06 08:54