问题描述
|
我想阅读用户输入,例如:
char *text = new char[20] ;
cin >> text ;
但是如果用户输入\“ hello \”,我希望其他空字符都用空格或-
填充,例如:
\"hello------------------------\"
我怎样才能做到这一点?
解决方法
没有标准且快速的方法来执行此操作。我可以想到一些选择。
假设我们有:
char *text = new char[20];
cin >> text;
注意-我们需要知道容量为20!我建议您为此使用一些常量,尤其是如果该常量也将用于其他字符串时。
好吧,第一个选择-使用std::stringstream
std::stringstream ss;
ss << setw( 20 - 1 ) << setfill( \'-\' ) << text;
// ^^^^ we need one byte for the \'\\0\' char at the end
ss >> text;
但这相当慢。
手工填写字符:
int length = strlen( text );
for( int i = length; i < 20 - 1; ++i ) // again - \"20-1\" - \'\\0\'
{
text[ i ] = \'-\';
}
text[ 20 - 1 ] = \'\\0\'; // don\'t forget to NULL-terminate the string
根据我的看法,最好的方法是-摆脱这些char*
的东西(您已将问题标记为c ++),而仅使用std::string
。
std::string sText;
std::cin >> sText;
sText.resize( 20,\'-\' ); // NOTE - no need to NULL-terminate anything
瞧! (:
这种方法更加清晰,您不必在末尾使用ѭ10(有时不是那么简单,尤其是在delete[]
之前有一些例外的情况下-这会给您100%的内存泄漏。当然,您总是可以使用智能指针..但是为此使用智能指针?!:))
当然,您可以编写19
而不是20-1
,我只是想“突出显示”-1
,以防您使用某些常量。
, 你们没人说过有关空终止符-\'\\ 0 \'的任何信息。在C / C ++中使用字符串时,这确实很重要。例如,如果您希望文本的长度为20个符号,则应为21个字符分配内存。这仅供Ata参考。您的问题的答案是:
char *text = new char[21];
//start initialization
for (int i=0;i<20;i++) {
text[i] = \'-\';
}
text[20] = \'\\0\';
//end initialization
cout << \"Your input: \" << endl;
cin >> text;//get the user input
text[strlen(text)]=\'-\';//change the automatically added \'\\0\' with \'-\'
cout << text << endl;
请记住,您还应该检查用户输入的时间是否比分配的内存长。
编辑:嗯,基里尔比我快(而且更精确)。 :)
, 您可以通过多种方式执行此操作。例如,假设您有一个充满19 \“-\”:的字符串(请注意,您用20定义了数组,您只能得到19个实字符以及最后的\\0
:
const char* dashes = \"--------------------\";
然后在编写时读取字符串:
char *text = new char[20] ;
cin >> text ;
然后您可以使用ѭ19copy复制其余字符,使用strlen
确定读取字符串的长度:
strcat(text,dashes + strlen(text));
这会将其余的“ 22”添加到文本中。请注意,我将该特定数量添加到dashes
指针中。
最后,>>
只会读一个字。要阅读完整的输入行,您必须使用getline
。