[英]#include <fstream> visual c++ 2010 not working properly
我知道標題有點模糊,但我現在想不出更好的標題。 我的代碼摘錄如下:
#include<iostream>
#include<fstream>
int main(){
ifstream f("cuvinte.txt");
f.getline(cuvant);
return 0;
}
當我想從“ cuvinte.txt”中讀取下一個單詞時,我寫f.getline(cuvant); 但我得到以下錯誤
error C2661: 'std::basic_istream<_Elem,_Traits>::getline' : no overloaded function takes 1 arguments
我不知道問題出在什么地方,不久前我偶然發現了這個問題,但仍然無法解決。
我不知道問題出在什么地方,不久前我偶然發現了這個問題,但仍然無法解決。
給參考 !
basic_istream& getline( char_type* s, std::streamsize count );
您需要提供大小,即cuvant
的可用空間量。
f.getline(cuvant, size);
^^^^
一種替代方法是使用更現代的工具:
string cuvant;
getline(f, cuvant);
您對各種形式的getline的熟悉程度似乎有些不穩定。 以下是它的一些簡單用法,供您參考:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
string filepath = "test.txt"; // name of the text file
string buffer; // buffer to catch data in
string firstLine; // the first line of the file will be put here
ifstream fin;
fin.open(filepath); // Open the file
if(fin.is_open()) // If open succeeded
{
// Capture first line directly from file
getline(fin,firstLine,'\n'); // Capture first line from the file.
cout << firstLine << '\n'; // Prove we got it.
fin.seekg(0,ios_base::beg); // Move input pointer back to the beginning of the file.
// Load file into memory first for faster reads,
// then capture first line from a stringstream instead
getline(fin,buffer,'\x1A'); // Capture entire file into a string buffer
istringstream fullContents(buffer); // Put entire file into a stringstream.
getline(fullContents,firstLine,'\n'); // Capture first line from the stringstream instead of from the file.
cout << firstLine << '\n'; // Prove we got it.
fin.close(); // Close the file
}
return 0;
}
使用以下示例文件:
This is the first line.
This is the second line.
This is the last line.
您將獲得以下輸出:
This is the first line.
This is the first line.
getline
的原型是:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
因此,正如錯誤消息明確指出的那樣,您不能使用一個參數來調用它...
假設cuvant
是std::string
,正確的調用是
std::getline(f, cuvant);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.