簡體   English   中英

輸入帶有兩個句號的字符串

[英]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;
}

該字符串的長度“思想就是一切。您認為自己變成了什么。” 是50,數組tem的大小也是50。cin需要在字符串末尾使用空終止符(“ \\ 0”)。 這就是為什么它不打印第二個句號。

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int main(){
    char tem[51];
    string pas="";
    cin.get(tem,51);
    cout<<tem<<endl;
    return 0;
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM