简体   繁体   English

将输入读取为C样式的字符串

[英]Reading input into a C-style string

I am working on a project for my programming class that requires me to work with strings. 我正在为我的编程课开发一个项目,该项目需要我使用字符串。 The program begins by asking the user to input a phrase. 该程序首先要求用户输入短语。 Normally I would declare something such as: 通常,我会声明以下内容:

    string phrase;

Then I would use: 然后,我将使用:

    getline(cin,phrase);

However, the professor told the class that we aren't allowed to use the string class, we must use only c-based strings. 但是,教授告诉班级我们不允许使用字符串类,我们只能使用基于C的字符串。 I could be wrong but I believe that c-based strings look something like this: 我可能是错的,但我相信基于C的字符串如下所示:

    char phrase[12] = "hello world";

If this is what my professor means by c-based strings, then I do not know how to input a phrase into them. 如果这是我的教授基于c的字符串的意思,那么我不知道如何在其中输入短语。 When I attempt this, the program only stores the first word of the phrase and stops at the first space it sees. 当我尝试这样做时,该程序仅存储该短语的第一个单词,并停在它看到的第一个空格处。 For example: 例如:

    char phrase[12];

    cin >> phrase;

//input: hello world

    cout << phrase;

//output: hello

Any advice would help and would be greatly appreciated, thank you. 任何建议都会有所帮助,非常感谢,谢谢。

You need to use cin.getline(var_id, var_length) and not cin >> var_id , which actually stops storing the input in the variable when it encounters a space or a new line . 您需要使用cin.getline(var_id, var_length)而不是cin >> var_id ,这实际上停止存储在变量输入,当它遇到一个spacenew line

If you want to know more about cin.getline and what problems its use can cause, you can have a look to this post: Program skips cin.getline() 如果您想了解有关cin.getline更多信息,以及它的使用可能引起什么问题,可以看一下这篇文章: 程序跳过cin.getline()

If you are reading input into a static char array you can use sizeof(charArray) to determine its maximum lengh. 如果将输入读取到静态char数组中 ,则可以使用sizeof(charArray)确定其最大长度。 But take into consideration that the last symbol will be end of line, so you can read maximum length-1 symbols into this array. 但是要考虑到最后一个符号将是行尾,因此您可以将最大长度为1的符号读入该数组。

char phrase[12] ;
cin.getline(phrase, sizeof(phrase));

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

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