Cin.get() 在文件被打开后 ifstream.

Cin.get() after file is opened with ifstream

本文关键字:ifstream 文件 get Cin      更新时间:2023-10-16

我之前发布了类似的代码,但我认为现在这是一个不同的问题。我只是想不通为什么我的运行代码不会超过"文件打开"。("-e"打印出来,"-d"不打印)我正在尝试打开我的文件,使用命令行选项来确定我是否会打印出一定的字符倍数。

例如,a.out -d 2 <样本.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