簡體   English   中英

如何從文本文件寫入數組以及從數組寫入文本文件?

[英]How to write from text file to array and from array to text file?

我當時正在做一個小項目,用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();

問題是這就是我的輸出文件的樣子。 我得到的是這些符號而不是文字... 在此處輸入圖片描述

任何幫助將不勝感激!

一些技巧,如何在現代C ++中進行編程。

  • 不要將整個std命名空間帶入您的代碼中- 為什么“使用命名空間std”被視為不良做法?
  • 代替傳統數組,使用std :: vector;
  • 不要評論明顯的例子。 !file.is_open()可能會在代碼修改后導致陳舊的注釋,並且注釋不會被修改。 使代碼顯而易見。
  • 不需要在塊末尾關閉文件(析構函數為您完成)
  • 使用標准的可用算法(例如std :: swap)
  • 使用有意義的變量名

--

#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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM