我試圖創建一個簡單的(模塊化的)C++程序,讀取用戶輸入並將其吐出。C++指針問題
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void _printOut(char * output)
{
cout << output << endl;
}
char * readUserInput()
{
char userInput[256];
cin >> userInput;
return userInput;
}
int _tmain(int argc, _TCHAR* argv[])
{
_printOut("Enter your name: ");
char * userName = readUserInput();
_printOut("Hello");
_printOut(userName);
system("pause");
return 0;
}
輸入您的姓名: AAAA 你好 ╠╠╠╠╠╠╠╠ 按任意鍵繼續。 。 。
,如果我在readUserInput功能打印出userInput變量它打印出什麼輸入。然而,嘗試在_tmain函數中將userInput變量存儲打印爲userName會導致打印出不可理解的字符序列。即。 ╠╠╠╠╠╠╠╠。 據我的猜測,這可能是由指針問題引起的,但據我所知,我正確地引用了所有內容。
調試這樣的代碼: 在這一行:_printOut( 「你好」);在方法中:_tmain [userName =「abcdefg」] at this line:_printOut(userName);在方法_tmain [用戶名=「†UX」]
所以我想知道如何在不分配或兩條線之間操縱它的用戶名的值正在改變。一旦超出範圍
的問題是,你使用'C字符指針++'。改用'std :: string'。 – stefan
使字符串函數而不是複雜的字符指針。 –