簡體   English   中英

如何使用c字符串讀取.txt文件?

[英]How to read a .txt file using c-strings?

我正在為一個學校項目工作,我需要從文件中讀取文本。

聽起來很容易,除了我的教授對該項目施加了限制: NO STRINGS (“不允許使用字符串數據類型或字符串庫。”)

我一直在通過使用char數組解決這個問題。 但是,我不確定如何使用char數組從文件中讀取。


這是另一個網站的示例 ,說明如何讀取字符串的文件。

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

重要的一行是while ( getline (myfile,line) );

getline接受ifstream和字符串 (非char數組)。

任何幫助表示贊賞!

使用cin.getline 請參考此站點以獲取格式: cin.getline

您可以這樣寫:

ifstream x("example.txt");
char arr[105];
while (x.getline(arr,100,'\n')){
    cout << arr << '\n';
}

ifstream有一個名為get()的方法,該方法將文件的內容讀取到char數組中。 get()以指向數組的指針和數組的大小為參數; 然后將數組填充到給定的大小(如果可能)。

get()返回之后,使用gcount()方法確定已讀取多少個字符。

然后,您可以使用一個簡單的邏輯循環,以size為單位的size將文件內容重復讀取到一個數組中,並將讀取的所有塊收集到一個數組或std::vector

您可以使用int i = 0; while (scanf("%c", &str[i ++]) != EOF) int i = 0; while (scanf("%c", &str[i ++]) != EOF)判斷文本輸入的結尾。 str是您想要的char數組包含換行符,而i是輸入大小。

您還可以使用while(cin.getline())以C ++樣式在每個循環中按行讀取: istream& getline (char* s, streamsize n, char delim ); 就像下面這樣:

const int SIZE = 100;
const int MSIZE = 100;
int main() {
    freopen("in.txt", "r", stdin);
    char str[SIZE][MSIZE];
    int i = -1;
    while (cin.getline(str[++ i], MSIZE)) {
        printf("input string is [%s]\n", str[i]);
    }    
}

暫無
暫無

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

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