【问题标题】:redirecting std::cin stream back and forth来回重定向 std::cin 流
【发布时间】:2015-04-28 00:32:51
【问题描述】:

我想从 *.txt 读取我输入的第一部分,然后从用户那里手动获取其余部分。 例如:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string a[100];
    for (int i=0;i<100;i++)
        cin >> a[i];
    for (int i=0;i<100;i++)
        cout << a[i] << endl;
}

如果我像 ./a.out 将输入流重定向回控制台,以便我从用户那里获得其余部分?

【问题讨论】:

  • 如果您想切换输入类型,则不应使用重定向。 fstream 会更好

标签: c++ redirect inputstream stdin


【解决方案1】:

你说:

我想从 *.txt 读取我输入的第一部分,然后从用户那里手动获取其余部分。

如果这是唯一的要求,我建议改变策略。

  1. 从命令行获取输入文件的名称。
  2. 从文件中读取尽可能多的数据。
  3. 然后切换到从cin读取其余数据。

例如:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv)
{
   string a[100];
   int count = 0;

   if ( argc > 1 )
   {
      ifstream infile(argv[1]);
      while (count < 100)
      {
         infile >> a[count];
         if ( infile )
         {
            ++count;
         }
         else
         {
            break;
         }
      }
   }

   for (int i=count;i<100;i++)
      cin >> a[i];
   for (int i=0;i<100;i++)
      cout << a[i] << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2011-06-12
    • 2021-03-24
    • 2014-08-10
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多