问一个弱弱的 C++primer 中的问题

2015-08-23 11:46:52 +08:00
 yf

int _tmain (int argc, _TCHAR* argv[])
{
string filename="hello.txt";
ifstream input;
input.open (filename.c_str ());
if (input.is_open ())
{
cout<<"opened"<<endl;
}
if (!input )
if (input.bad ())
cout<<"bad"<<endl;
if (input.fail ())
cout<<"fail"<<endl;
return -1;
f (input );
system ("pause");
return 0;
}

istream &f (istream &in )
{
string temp;
while (in>>temp,!in.eof ())
{
if (in.bad ())
throw runtime_error ("IO stream corrupted");
if (in.fail ())
{
cerr<<"bad data,try again!";
in.clear ();
in.setstate (istream::eofbit );
continue;
}
cout<<temp<<endl;
}
in.clear ();
return in;

}

代码如上,总是跳到文件打开失败语句, hello.txt 文件我放在与 exe 文件同一个目录下。
百思不得其解啊?为什么呢?

1547 次点击
所在节点    C
13 条回复
Smilecc
2015-08-23 12:06:27 +08:00
Debug 的时候把 hello.txt 放在工程目录里,就是和代码文件放一起。
bazingaterry
2015-08-23 12:08:00 +08:00
提几个建议:
这种问题在 Stack Overflow 或 SegmenFault 提问可能会更快有回答
还有贴代码请用 gist
没了缩进怎么帮你看 ToT
oska874
2015-08-23 12:38:08 +08:00
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (int argc, char *argv[])
{
string filename="hello.txt";
char bb[10];
ifstream input;
input.open (filename.c_str ());
input.getline (bb,10 );
cout<<bb<<endl;
return 0;
}
可以打开,并且读出内容,不报错。
ljbha007
2015-08-23 13:56:12 +08:00
这么多 if 还不用缩进怎么看啊
shakespark
2015-08-23 17:04:59 +08:00
建议每个 if 后都用{}括住内容
rogerchen
2015-08-23 19:36:38 +08:00
C++ Primer 里边会用 _tmain 做入口? 我书读得少不要骗我。
ooxxcc
2015-08-23 19:56:16 +08:00
目测因为 if 没有加括号导致逻辑不是按照你想的那样来的
ototsuyume
2015-08-23 20:00:05 +08:00
目测楼主用 VS 调试,然而 vs 调试时的当前目录跟生成的可执行文件所在的目录不是同一个
forcecharlie
2015-08-23 20:08:04 +08:00
@Smilecc 说的是正确的,如果没有指定文件的绝对路径,那么,程序就必须在当前目录下,如果你使用 Visual Studio 调试或者运行程序,那么这个时候的当前目录是程序源文件目录,并不是 Debug 目录,你如果在 Debug 目录中启动程序,一般是能够打开文件的。如果你要打开 exe 所在目录的文件,应当使用 GetModuleHandle (nullptr,buffer,MAX_PATH ) 取得 exe 的绝对路径,并使用 PathRemoveFileSpec 去除 exe 文件名,然后使用 strcat (wcscat ) 拼接路径。最后通过绝对路径打开文件。
ncwhale
2015-08-23 21:27:41 +08:00
程序运行时的环境变量的当前目录( PWD )不是你预想的位置,如果是 VS 请将 hello.txt 放到源代码目录,或者右键工程->属性->调试->工作路径 然后自己设置到 hello.txt 所在目录喵。
yf
2015-08-29 08:32:29 +08:00
@bazingaterry ok 感谢并且接纳你的意见!
mr8fazai8fa8
2016-12-08 22:25:38 +08:00
求帮忙+我 weixin fangxiaobu1
mr8fazai8fa8
2016-12-08 22:29:47 +08:00
楼主帮忙

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/215303

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX