我正在开发一个用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
任何帮助将不胜感激!
答案 0 :(得分:1)
有关如何使用Modern C ++进行编程的一些提示。
-
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm> // until c++11
#include <utility> // since c++11
using std::cout;
using std::endl;
using std::string;
int main()
{
std::ifstream fileToRead( "lab01.txt" );
std::ofstream fileOut( "lab01_out.txt" );
if ( !fileToRead.is_open() || !fileOut.is_open() )
{
cout << "Error, file was not oppened!" << endl;
return -1;
}
std::vector< string > strings;
string readString;
while ( fileToRead >> readString )
{
strings.push_back( readString );
}
const auto stringsCount = strings.size();
// bubble sort
for ( auto lastPosition = stringsCount - 1; lastPosition > 0; lastPosition-- )
{
for ( std::size_t checkedPosition = 0; checkedPosition < lastPosition; checkedPosition++ )
{
if ( strings[ checkedPosition ] > strings[ checkedPosition + 1 ] )
{
std::swap( strings[ checkedPosition ], strings[ checkedPosition + 1 ] );
}
}
}
for ( string str : strings )
{
cout << str << endl;
fileOut << str << endl;
}
}