【发布时间】:2020-10-08 00:00:42
【问题描述】:
如何在 C++ 中打印出字符数组 (msg)?我的输出打印了我在不同行上加密的单词,而不仅仅是一行。此外,“输入一行文本或'完成'”最终会重复。我假设它是因为单词之间的空格。我该如何解决?任何建议都会有所帮助!
int main()
{
ofstream outputFile;
string fileName; //initiate variables
char msg[100];
int i;
std::cout<< "Enter file name to encrypt: "; //get file name from user
std::cin >> fileName; //save file name
outputFile.open(fileName);
while(true){
std::cout<< "Enter a line of text or '" << "done" << "' to quit: "; //get line of text from user
std::cin>> msg; //send line of text to message array
if (msg[0] == 'd' && msg[1] == 'o' && msg[2] == 'n' && msg[3] == 'e'){//check if done is input
break; //if done is entered, break program
}
else{
for(i = 0; (i < 100 && msg[i] != '\0'); i++){ //loops thru encrypting each letter
msg[i] = msg[i] + 1; //encrypt text
}
outputFile << msg << endl; //send encrypted string/message to file from user
std::cout << "Encrypted message: " << msg << endl; //print encrypted text to screen
}
}
outputFile.close(); //close file
return 0;
}
【问题讨论】:
-
你为什么使用
char的数组而不是std::string?文件名为string的事实表明您知道 C++ 样式的字符串。 -
对于
break:将 AND&&替换为 OR||!! -
另外,请举个简单输入错误输出的例子
-
@Damien 您建议对以
'd'开头的每个单词进行打断或,第二个字母为'o'或 987654330@ 作为其第三个字母或 以'e'作为其第四个?&&的使用对我来说看起来是正确的(但它缺少对第五个字符'\0'的检查)。 -
@JaMiT 对。抱歉,我读得太快了。
标签: c++ arrays loops printing char