从std::cin读取多行

Read multiple line from std::cin

本文关键字:读取 cin std      更新时间:2023-10-16

我正在编写一个单元测试,并尝试从stdin或cin读取一些POST数据。数据如下:

callCount=1
page=/cs/admissions/admissions_tracker_result.jhtml?schoolId=436&classYear=2020
httpSessionId=xQIX_WS2vyua_JfEEKL0zAVRkxCLzMv-RM8ZJYuWfkaoA_IB6Ynn!788428762
scriptSessionId=5A7188C7ABF4B9F05D7CEB361E670361570
c0-scriptName=AdmissionScattergramService
c0-methodName=renderChart
c0-id=0
c0-e1=string:true
c0-e2=string:true
c0-e3=string:true
c0-e4=string:true
c0-e5=string:true
c0-e7=string:8
c0-e8=string:2
c0-e9=string:4
c0-e10=string:3
c0-e11=string:6
c0-e12=string:7
c0-e6=Array:[reference:c0-e7,reference:c0-e8,reference:c0-e9,reference:c0-e10,reference:c0-e11,reference:c0-e12]
c0-e13=string:true
c0-e14=string:true
c0-e15=string:true
c0-e16=string:true
c0-e17=string:true
c0-e18=string:true
c0-e19=string:true
c0-e20=string:true
c0-e22=string:1
c0-e23=string:2
c0-e24=string:3
c0-e25=string:4
c0-e26=string:0
c0-e21=Array:[reference:c0-e22,reference:c0-e23,reference:c0-e24,reference:c0-e25,reference:c0-e26]
c0-e27=string:true
c0-e28=string:true
c0-e30=string:AL
c0-e31=string:AK
c0-e32=string:AR
c0-e33=string:AS
c0-e34=string:AZ
c0-e35=string:CA
c0-e36=string:CO
c0-e37=string:CT
c0-e38=string:DC
c0-e39=string:DE

当我粘贴到调试器中时,程序会自动启动运行程序。我试图修改我的代码,并使用std::getline(std::can, post)而不是std::cin>>post;。但是,它不起作用。这是代码:

 std::string url;
  std::string post;
  printf("enter the urln");
  std::cin>>url;
  printf("enter the post datan");
  std::string line;
    while (true) {
      getline(std::cin, line);
      if (line.empty()) {
        break;
      }
    post += 'n' + line;
    }

看起来getline()是非阻塞的。而变量std::string post则为空。

getline实际上正在阻塞。你面临的问题是因为这条线:

std::cin>>url;

它从一行读取url,但不读取换行符。当您调用getline时,流就在url后面的换行符前面,然后您读取它,得到一个空行。要解决这个问题,只需在读取url后调用getline一次,然后再进入循环。