2017-03-09 72 views
1
string input; 
    string input2; 
printf("What is your name?\n-->"); 
getline(cin, input); 
std::string nameObj = "{ \"name\": " + '"' + input + '"' + " }"; 
printf("What do you want to send?\n-->"); 
getline(cin, input2); 
std::string jsonObj = "{ \"content\": " + '"' + input2 + '"' + ", \"tts\": true }"; 

它要求输入,但它不会做任何事情。我需要它将其放入input2和input中,但它不会。Getline没有输入

+1

您真的应该在读写后检查流状态,以查看操作是否失败并“断开”流。 – user4581301

回答

0

你的代码几乎是正确的,唯一不能做你想做的事情就是像在JSON构造中那样添加charchar*。写这样的:

string input; 
string input2; 
printf("What is your name?\n-->"); 
getline(cin, input); 
std::string nameObj = "{ \"name\": \"" + input + "\" }"; 
cout << nameObj << endl; 
printf("What do you want to send?\n-->"); 
getline(cin, input2); 
std::string jsonObj = "{ \"content\": \"" + input2 + "\", \"tts\": true }"; 
cout << jsonObj << endl; 

http://ideone.com/zY1LFg

char s为基本号码,让你在不经意间做的,而不是连接字符串和字符指针运算。 C++的内置类型真的很原始,例如你也不能连接原始的char* s;要做到这一点,你总是需要把它们包装在std::string("...")

而不是连接,你可以看看stringstream建立你的JSON字符串,同时避免由重复串联字符串造成的复制。

您还应该通过执行if (!cin.good()) { /* handle error */ }来检查cin流是否正常。错误处理通常涉及用cin.clear()清除流的状态。

+0

非常感谢! –

+0

如果这对你有所帮助,请注册并接受这个答案;) –

+0

我点击了绿色的选中标记,但是我不能留下优惠,因为没有足够的代表或什么。 –