我之前发布了类似的代码,但我认为现在这是一个不同的问题。我只是想不通为什么我的运行代码不会通过“infile open”。 (“-e”打印出来,“-d”不打印)我正在尝试打开我的文件,使用命令行选项来确定我是否将打印出特定倍数的字符。
例如,a.out -d 2
int main (int argc, char *argv[])
{
ifstream infile;
if (infile.good())
printf("infile open \n");
int c;
int number = 0;
int count = 0;
string str1 = argv[1];
string str2 = "-d";
string str3 = "-e";
if (str1.compare(str2) == 0)
{
printf("entered -d\n");
c = infile.get();
while(!infile.eof()) {
number = atoi(argv[2]);
if (count == number)
{
cout.put(c);
count = 0;
}
else
count++;
c = infile.get();
}//end while
}//end if
if (str1.compare(str3) == 0)
printf("entered -e\n");
}//end main
最佳答案
infile
永远不会打开:
ifstream infile; // Does not open a file as no file name is supplied.
使用 cin
或传递 "sample.txt"
作为另一个命令行参数并打开它:
ifstream inFile(argv[3]);
if (inFile.is_open())
{
}
其他要点:
- 使用
std::cout
而不是混合使用printf()
和std::cout
。 atoi()
如果参数无效或参数是有效的0
,则返回0
。参见strtol()
寻找替代方案。- 没有理由在
while
的每次迭代中转换argv[2]
。只需在while
之前执行一次即可。 - 在访问
argv
的元素之前始终检查argc
,以避免无效的内存访问。 std::string
实例可以使用operator==
进行比较.
关于c++ - 使用 ifstream 打开文件后的 Cin.get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621271/