簡體   English   中英

.txt 文件到字符數組?

[英].txt file to char array?

我一直在嘗試讀取帶有以下文本的 .txt 文件:

調試的難度是最初編寫代碼的兩倍。 因此,如果您盡可能聰明地編寫代碼,根據定義,您就不夠聰明來調試它。 - 布賴恩 W. Kernighan *

但是,當我嘗試將 .txt 文件發送到我的 char 數組時,打印出除“調試”一詞之外的整個消息,我不知道為什么。 這是我的代碼。 它一定是我看不到的簡單東西,任何幫助將不勝感激。

#include <iostream>
#include <fstream>

using namespace std;

int main(){

char quote[300];

ifstream File;

File.open("lab4data.txt");

File >> quote;


File.get(quote, 300, '*');


cout << quote << endl;
}

File >> quote;

將第一個單詞讀入數組。 然后對File.get的下一次調用將復制您已閱讀的單詞。 所以第一個字就丟了。

您應該從代碼中刪除上面的行,它會正常運行。

我通常建議使用std::string而不是 char 數組來讀入,但我可以看到ifstream::get不支持它,最接近的是streambuf

要注意的另一件事是檢查您的文件是否正確打開。

下面的代碼就是這樣做的。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){

    char quote[300];
    ifstream file("kernighan.txt");

    if(file)
    {
        file.get(quote, 300, '*');
        cout << quote << '\n';
    } else
    {
        cout << "file could not be opened\n";
    }    
}

ifstream對象可轉換為bool (或 c++03 世界中的void* ),因此可以測試其真實性。

一個簡單的 char by char 讀取方法(未測試)

包括

#include <fstream>

using namespace std;

int main()
{ 
    char quote[300];
    ifstream File;
    File.open("lab4data.txt");
    if(File)
    {
         int i = 0;
         char c;
         while(!File.eof())
         {
             File.read(&c,sizeof(char));
             quote[i++] =c;
         }   
         quote[i]='\0';          
         cout << quote << endl;
         File.close();
    }

}

暫無
暫無

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

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