如何让字符数组在一行而不是多行中打印出来?
how to get character array to print out in one line and not multiple in c++?
如何在 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
相关文章:
- 打印字符数组地址的正确方法
- c ++控制台应用程序,如何在控制台外部打印字符
- 无法使用 swprintf 在 WCHAR* 中打印字符*
- 存储和打印字符,但输出不是预期的
- 如何使 printf 以与 NSLog 相同的方式打印字符缓冲区?
- 在带有 (void*) 强制转换的字符串中打印字符的内存地址
- C++无法打印字符变量
- 无法打印字符向量C++向量
- 为什么在编辑 fastq 文件并将输出写入新的 fastq 文件时引入不可打印字符?
- C :如何询问文件名并打印字符数组
- 循环中的 Cout 不会按定义的字符逐个打印字符
- (C++) 打印字符数组字符串的单词时出现问题
- 用putchar在屏幕上打印字符
- 在C 中使用继续语句的打印字符
- 在 for 循环 c++ 中打印字符
- 使用while和if递归打印字符
- 打印字符数组 c++
- 如何使用Xcode中的Unicode打印字符╔(和其他字符)
- cout.put() 是否推荐使用 cout<< 打印字符
- C++ 中的密码 |打印字符后删除字符