[英]Read line from file: Unable to use getline()
我的任務是編寫一個 function 從文本文件中讀取一行(重命名為.dat
,但它只包含文本),但由於以下幾點,我無法選擇解決方案:
我正在使用Borland C++ Version 5.02
,不,我不能下載另一個編譯器,因為我的筆記本電腦沒有管理員權限,而且知道所需密碼的人要到下周才會出現。
編譯器不接受using namespace std
,也不接受getline()
,無論是否包含string
和iostream
。
我正在嘗試找到解決方案或至少是最小的方法,但我找不到。
所以我的問題是:如何在不使用getline()
的情況下從簡單的文本文件中讀取一行( cin.getline
有效,而來自string
或fstream
的無效)? 文本文件包含如下幾行:
1234;12.05.03;08:44:23; XY12-AB;A1-12;超時
2345;12.05.03;09:04:34;XY1-CD;A22-9;連接被拒絕
和;
之間的數字/字母需要存儲在變量中,以便可以使用它們。
我不是要你寫我的代碼,但我真的很沮喪,我的導師也幫不上忙。
長壽和繁榮,我。
http://www.cplusplus.com/reference/string/string/getline/
如果您不能使用(您不應該使用)
using namespace std
然后使用::運算符引用您的命名空間
例如:
std::string
現在嘗試使用std ::編寫自己的代碼,如果仍然無法注釋,請添加注釋。
另外,除了std :: getline()以外,還有很多其他選項可以讀取文本行。
參考: 逐行讀取文件
選項1:
嘗試使用C的fgets()函數。
選項2:您提到cin.getline()有效。 您可以使用輸入文件freopen stdin,然后cin指向所提到的文件。 之后,cin.getline()將從文件中讀取:
缺點:在freopen之后,您將無法接受用戶的任何輸入。
示例:請注意,尚未使用g ++嘗試過此方法,但我想它也應與Borland一起使用。
#include <iostream>
#include <stdio.h>
int main() {
char buf[1000];
freopen("somefile.dat", "r", stdin);
while (cin.getline(buf, sizeof(buf)).good()) {
// Now buf contains a line
// Do something with it
}
return 0;
}
嘗試使用
getline(cin >> ws, variableName);
但首先,你必須使用
using namespace std;
我在將結構上的多維數組用於文件時遇到了同樣的問題,我嘗試了不同的方法。 但后來我嘗試了這個,它對我有用。
所以在我的情況下它會是這樣的
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myFile;
myFile.open("test.txt");
int count = 0;
while (!myFile.eof())
{
getline(myFile >> ws, data[count].string1);
getline(myFile >> ws, data[count].string2);
myFile >> data[count].int1;
for (int i = 0; i < data[count].int1; i++) {
getline(myFile >> ws, data[count].data2[i].string3);
}
count++;
}
return 0;
}
更多信息: https://www.geeksforgeeks.org/problem-with-getline-after-cin/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.