如何让字符数组在一行而不是多行中打印出来?

how to get character array to print out in one line and not multiple in c++?

本文关键字:打印 字符 数组 一行      更新时间:2023-10-16

如何在 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] != ''); 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;
}

代码使用operator>>来获取用户输入。这是一个基于单词的格式化输入函数。它跳过前导空格,然后提取一系列非空格字符。也就是说,它提取下一个输入单词。获取下一个单词后,对其进行处理,开始新的输出行,提示用户输入更多输入,然后重复。当每行有多个单词时,计算机不会等待更多输入(尽管有提示(,并且您会看到您描述的输出。

由于您要查找一行输入,因此您应该使用获取整输入而不仅仅是一个单词的 API。准备好接受这个 API 的惊人名称了吗?它被称为getline(),或者更准确地说std::istream::getline因为您被困在使用字符数组而不是字符串。

std::cin.getline(msg, 100);

使用std::string不会改变结果,但它会使我更容易找到文档。字符串的operator>>版本也是基于单词的。字符串的换行 API 是一个免费函数,std::getline.


其中一个测试的建议输入:

Done
DONE
donegal is in Ireland
done?
done!
done