Cin.get() 在文件被打开后 ifstream.
Cin.get() after file is opened with ifstream
我之前发布了类似的代码,但我认为现在这是一个不同的问题。我只是想不通为什么我的运行代码不会超过"文件打开"。("-e"打印出来,"-d"不打印)我正在尝试打开我的文件,使用命令行选项来确定我是否会打印出一定的字符倍数。
例如,a.out -d 2 <样本.txt>样本.txt>将每隔两个字母打印出一次。
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 -dn");
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 -en");
}//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
,以避免无效的内存访问。 - 可以使用
operator==
比较std::string
实例。
当在
命令行上运行这样的东西时:"a.out
相关文章:
- ifstream文件在从行中读取时被清除
- 是否可以在没有真实文件的情况下创建 ifstream
- 虽然循环不读取整个 ifstream 文件
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- ifstream 读取的字符与文件中写入的字符不同
- 如何使用 ifstream 检查文件中变量的类型?
- 尝试使用 Ifstream 打开.txt文件时C++问题
- 如何确保我的"ifstream"文件对象指向的文件内容已更新?
- 为什么我可以将 ifstream 文件置于 if 条件?
- 将 ifstream 文件和每一行读取到数组中
- 为什么 ifstream 文件中的换行符 - 当被此代码读取时 - 占用 2 个字节
- 带有引号+组合目录 c++ 的 ifstream 文件目录
- 函数不读取 ifstream 文件
- 尝试将数字放入 ifstream 文件中的变量中
- Ifstream文件不会打开,尽管一切似乎都已就绪(c++)
- ifstream 文件打开导致程序'terminate in an unusual way'
- 从ifstream文件读取时给出了错误的大小
- 通过函数传递ifstream文件时出现错误
- 在fstream/ifstream文件中使用多个函数