简体   繁体   English

C++ 操作字符串,可以打印索引字符但不能打印完整字符串

[英]C++ Manipulating Strings, can print index chars but not complete string

I am trying to mask a password for a project I'm doing on OS X. Every masked character is appended to the string named password.我正在尝试为我在 OS X 上执行的项目屏蔽密码。每个被屏蔽的字符都附加到名为 password 的字符串中。 But when I try to print or use the string I get nothing.但是当我尝试打印或使用字符串时,我什么也没得到。 However if I try to print an element of the string, I am able to.但是,如果我尝试打印字符串的元素,则可以。 Example.例子。 cout<< password; cout<<密码; wont print anything but cout << password[0] will print the first character of the string.除了 cout << password[0] 将打印字符串的第一个字符外,不会打印任何内容。

What am I doing wrong?我究竟做错了什么?

#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;
}

When you define the object password it is starting out as empty which means any indexing into it will be out of bounds and lead to undefined behavior .当您定义对象password它开始为,这意味着对它的任何索引都将超出范围并导致未定义的行为

You don't need the index variable i , and you should append characters to the string:您不需要索引变量i ,您应该字符附加到字符串:

password += c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM