我想使用字串物件獲取人名。但是在我的代碼中,如果我將兩部分名稱用空格分隔,則只顯示第一部分。我的理解是 .c_str() 回傳一個指向存盤字串的指標,終端為空。為什么空間有問題。我是 C 的新手,使用的是 Code::Blocks 13.12。這是我在我撰寫的另一個程式中遇到的問題的簡化版本。提前致謝。
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
string sCusName;
cout << "Please enter your name-> ";
cin >> sCusName;
int xsize = sCusName.length();
char *tempBuffer = new char[xsize 1];
strncpy(tempBuffer, sCusName.c_str(),xsize 1);
cout << tempBuffer << " is a beautiful name." << endl;
return 0;
}
當我輸入單個零件名稱時,程式運行正常。但是如果我輸入用空格分隔的兩部分名稱。只收錄了第一部分。
uj5u.com熱心網友回復:
cin使用getline() 函式讀取多字字串是不可能的,它getline()有兩個引數 cin 和字串變數,例如:
int main()
{
string sCusName;
cout << "Please enter your name-> ";
getline(cin,sCusName);
cout << sCusName << " is a beautiful name." << endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535257.html
標籤:细绳c-str
下一篇:從字串中洗掉小數
