[英]C++ Manipulating Strings, can print index chars but not complete string
我正在嘗試為我在 OS X 上執行的項目屏蔽密碼。每個被屏蔽的字符都附加到名為 password 的字符串中。 但是當我嘗試打印或使用字符串時,我什么也沒得到。 但是,如果我嘗試打印字符串的元素,則可以。 例子。 cout<<密碼; 除了 cout << password[0] 將打印字符串的第一個字符外,不會打印任何內容。
我究竟做錯了什么?
#include <termios.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
using namespace std;
int getch();
int main(){
char c;
string password;
int i=0;
while( (c=getch())!= '\n'){
password[i]=c;
cout << "*";
i++;
}
cout<< password;
return 0;
}
int getch() {
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
當您定義對象password
它開始為空,這意味着對它的任何索引都將超出范圍並導致未定義的行為。
您不需要索引變量i
,您應該將字符附加到字符串:
password += c;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.