c++ - 使用 ifstream 打开文件后的 Cin.get()

标签 c++

我之前发布了类似的代码,但我认为现在这是一个不同的问题。我只是想不通为什么我的运行代码不会通过“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/

相关文章:

远程对象的 C++ 调用方法(类似于 RPC)

c++无法编译文件

c++ - QPushButton 不遵守水平扩展尺寸策略

c++ - 用于在 C++ 中管理平台特定代码的内联命名空间技术

c++ - 为父/子关系正确使用 unique_ptr

c++ - 如何通过openGL访问cuda上的数据?

c++ - 如何使用 CImg 显示少量图像(每个图像在单独的窗口中)?

c++ - 创建表时主键声明错误

c++ - (C++11) Variadic Ally 模板函数转发到另一个

c++ - 模板类的类型定义?