作者smalldulan (媽媽咪阿)
看板C_and_CPP
標題[問題] 字串輸出有亂碼
時間Sun Feb 22 22:35:23 2009
各位大大可以請教一個問題嗎?
我練習字串的時候
寫了讓使用者輸入字串然後將他輸出的程式
不知道為什麼~我字串長度要是訂的太大~
輸出後後面沒用到的部份就會出現亂碼?
請問這是我長度定義錯誤嗎?
以下是我的程式碼:
#include<iostream>
using namespace std;
int main()
{
int i=0;
char str[30];
cout<<"輸入想輸入的字串:";
cin>>str;
for(i=0;i<(sizeof(str)/sizeof(str[0]));i++)
{
cout<<str[i];
}
system("PAUSE");
return 0;
}
請各位大大幫幫我吧~我正在學習C++~是超新手~
請問問題是出在哪呢?還是解決得方法?
感謝~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.142.17.111
1F:→ james732:其實那個迴圈…直接用 cout << str; 就可以了 XDD 02/22 22:38
2F:→ james732:計算字串長度可用 strlen,請記得 #include <cstring> 02/22 22:40
3F:→ james732:用 strlen(str) 來取代 (sizeof(str)/sizeof(str[0])) 02/22 22:40
4F:→ james732:至於你的問題…印出sizeof(str)與sizeof(str[0])的值就知 02/22 22:43
5F:推 legnaleurc:請選擇std::string 02/22 22:49
6F:→ smalldulan:可以了~謝謝大大們的解答 02/23 01:48