[英]Read multiple line from std::cin
我正在編寫單元測試,並嘗試從 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 url\n");
std::cin>>url;
printf("enter the post data\n");
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
一次,然后再進入循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.