0
我正在研究一个小项目来练习C++中的I/O文件,但我无法弄清楚这个问题。我想编写和算法,在文本文件中按字母顺序重新排列单词(最好是气泡排序)。这是我到目前为止如何从文本文件写入数组和从数组写入文本文件?
ifstream file("lab01.txt");
ofstream fileOut("lab01_out.txt");
char s[20][10];//variable for copying the words
//check if file was oppened
if (!file.is_open()) {
cout << "Error, file was not oppened!" << endl;
return -1;
}
//copy words from file to 2d array
for (int i = 0; i < 20; i++)
file >> s[i];
char check[1];
//bubble sort
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 18 - i; j++) {
if (strcmp(s[j], s[j + 1]) > 0) {
strncpy_s(check, s[j], _TRUNCATE);//if not truncated error "buffer to small"
strncpy_s(s[j], s[j + 1], _TRUNCATE);
strncpy_s(s[j + 1], check, _TRUNCATE);
}
}
}
//printing array to output file and to console.
for (int i = 0; i < 20; i++) {
cout << s[i] << endl;
fileOut << s[i] << endl;
}
//closing files.
file.close();
fileOut.close();
问题是,这是我的输出文件的样子。我得到这些符号而不是字... enter image description here
任何帮助将不胜感激!
听起来好像您可能需要学习如何使用调试器来遍历代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
***我正在一个小项目来练习C++中的I/O文件***如果你真的这样做,我的建议是退出使用char数组而不是std :: string。 – drescherjm
对于初学者,我会将'char check [1];'更改为'char check [10];'。 –