[英]Inputting String with two fullstops
我需要輸入帶有兩個句號的字符串,但是此代碼輸入了最后一個句號。 當輸入為:“思想就是一切。您認為自己變成了什么。” 接下來是Enter鍵和“ sitdown”
該程序在tem
存儲:“思想就是一切。您認為自己成為什么”,它錯過了最后一個句號,而是將句號存儲在pas
:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
char tem[50];
String pas=""
cin.get(tem,50);
cin>>pas;
cout<<tem<<endl;
}
您分配的緩沖區大小為50個字符長,輸入的字符串也為50個字符長,但是cin.get
需要1個字符來終止0,因此它占用了句點。 使緩沖區51長並讀取51個字符。
#include <iostream>
int main()
{
char tem[51];
std::cin.get(tem, 51);
std::cout << tem << std::endl;
}
如果改用std::string
,則無需擔心輸入不適合緩沖區:
#include <iostream>
#include <string>
int main()
{
std::string tem;
std::getline(std::cin, tem);
std::cout << tem << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.