[英]Why the ifstream does not read anything
我正在使用ifstream
,但程序沒有從輸入文件中讀取任何內容。 程序運行在macOS 10.14,我的編譯器是clang 10.0.1,我把源代碼和輸入文件放在同一個文件夾下。
std::string contents;
std::vector<std::string> ContainerOfString;
int main(){
std::ifstream ifs;
ifs.open("test.txt");// test.txt is in the same folder with the source code
if(ifs){
while(ifs>>contents){
ContainerOfString.push_back(contents);
}
for(auto &i:ContainerOfString){
std::cout<<i<<" ";
}
}
return 0;
}
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
std::string contents;
std::vector<std::string> ContainerOfString;
int main()
{
std::ifstream ifs;
ifs.open("test.txt"); // test.txt is in the same folder with the source code
if (ifs)
{
while (ifs >> contents)
{
ContainerOfString.push_back(contents);
}
for (auto &i : ContainerOfString)
{
std::cout << i << " ";
}
}
else
{
std::cout << "file not found" << std::endl;
}
return 0;
}
有一種機制來檢查您的代碼是否找到了文本文件。 很可能您的文本文件拼寫錯誤,或者它與您的主代碼不在同一個目錄中,或者其他東西阻止了您的文件被讀取。 還要檢查文本文件是否為空,因為這也不會從您的代碼中生成任何 output。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.