【问题标题】:Cannot extract data from command line as expected无法按预期从命令行提取数据
【发布时间】:2013-01-30 15:03:22
【问题描述】:

我有一个 course0.dat 文件,第 1 行有一个 4,我想用我的 ifstream 程序提取它:

void processEnrollments (std::istream& courseFile);

int main (int argc, char** argv)
{

// Take input and output file names from the command line
ifstream coursesIn (argv[1]);

return 0;
}

void processEnrollments (istream& courseFile)
{
int numCourses;
courseFile >> numCourses;

cout << numCourses;

// Create the arrays we need
//!! Insert your code here
}

当我跑步时

program courses0.dat

我的测试是计算 32767 而不是 4。我的 .dat 文件与我的可执行文件位于同一目录中。

有什么线索吗?

谢谢

【问题讨论】:

  • 鉴于我们甚至不知道courses0.dat 中有什么内容,我们应该如何判断出了什么问题...
  • 我看不到你是如何得到任何输出的,因为 processEnrollments 甚至没有被调用。
  • 是的,好吧,你太依赖operator &gt;&gt; 来做“正确的事”。只需考虑文件中的额外乱码、空行等...转到std::getline 并从那里开始。
  • 我的第一句话是:“我有一个 courses0.dat 文件,第 1 行有一个 4,我想用我的 ifstream 程序提取:”
  • @nobody 对不起,我的意思是包括:processEnrollments (coursesIn);在我的主要;它在我的程序中,我只是忘记在帖子中包含它。

标签: c++ ifstream istream


【解决方案1】:

检查错误!将文件作为参数传递时尝试使用文件的完整路径。

我的猜测是courseFile &gt;&gt; numCourses; 失败,因为ifstream coursesIn (argv[1]) 找不到或无法访问该文件。

试试这个

if( courseFile >> numCourses )
    cout << numCourses;

那么它会输出什么吗?

【讨论】:

  • 感谢您的帮助 :) 您的回复是第一个实际上并没有听起来他们在对我说话的人。我很感激。我的问题是xcode。我从终端使用 g++ 编译,都在同一个目录中,似乎一切正常。
猜你喜欢
  • 2014-11-28
  • 2012-04-11
  • 1970-01-01
  • 2022-01-26
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
相关资源
最近更新 更多