【问题标题】:reading data from txt file, works in Visual Studio but fails in Xcode从 txt 文件读取数据,在 Visual Studio 中工作,但在 Xcode 中失败
【发布时间】:2014-06-30 01:54:15
【问题描述】:
#include <stream>  
#include <iostream>
#include <stream>
#include <iosfwd>
#include <string>

using namespace std;

int main(int argc, const char * argv[]) {
    string op = "original";
    ifstream file;
    file.open("sample.txt");
    if(!file) {
        cout << "Error: unable to open file." << endl;
    }
    else {
        while(!file.eof()) {
            file >> op;
            cout << op << endl;
        }
    }

    file.close();
    return 0;
}

sample.txt 仅包含单词five

我在 Visual Studio 中运行这段代码,输出是

five

我在 Xcode 中运行完全相同的代码(直接复制和粘贴,并且肯定会添加 data.txt),并且在命令行中打印的是

original

我看到的错误是

file >> op    

从未真正在 Xcode 中工作过。为什么?

【问题讨论】:

  • 如何打印任何东西?这绝对不是有效的 C++。
  • 请将真实代码粘贴到您的问题中。这不是你的程序。
  • @Afonso ASCII 和 UTF-8 对于“五”是一样的。
  • @user3703783,没有人知道包含的内容应该是什么,尤其是编译器。而&lt;stream&gt; 不是标准标题(有iostreamistreamostreamsstreamstrstreamfstream,也许还有其他)。但真诚地,感谢您回来。

标签: c++ xcode text


【解决方案1】:

这是如何从文本文件中获取字符串的示例

#include <fstream>

std::string getDataFromFile(std::string filepath)
{
   ifstream fin;


   std::ifstream file(filepath);
   std::string temp;
   stringstream fileData("");
   while(std::getline(file, temp)) {
       fileData << temp << "\r\n";
   }
   file.close();

   return fileData.str();

}

【讨论】:

    【解决方案2】:

    在第 20 行 (cout &lt;&lt; op &lt;&lt; "haha" &lt;&lt; endl;) 的 cout 语句中,必须删除 &lt;&lt; "haha" 的文字。或者,如果您的预期输出应该等于:

    five
    haha
    

    尝试这样做:

    cout << op << endl <<"haha";
    

    我确实发现这是一个很容易回答的问题。很抱歉我的答案没有正确输出:(。

    【讨论】:

    • 我看不出这应该如何解决问题中所述的问题?
    • 谢谢我更正了我的代码。真正困扰我的是 ""file >> op" 从来没有工作过。没有任何字符串加载到 op 中。这是为什么?
    • @πάνταῥεῖ 真的很抱歉!我也是stackoverflow的新手。现在变了
    猜你喜欢
    • 2016-04-01
    • 2017-12-04
    • 1970-01-01
    • 2013-05-09
    • 2013-09-19
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多