gpt4 book ai didi

c++ - 在 C++ 中读取文件时,您如何做到在文件末尾有换行符?

转载 作者:行者123 更新时间:2023-11-30 05:17:52 29 4
gpt4 key购买 nike

我写了这个有指南的程序,但是当它打印出指南时,它输出:

guideWould you like to run this program again (y/n):

但我希望它输出的是:

guide
Would you like to run this program again (y/n):

请注意,引导部分来自文件,而不是 cout 语句。我的代码如下所示:

#include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <fstream>

using namespace std;

int main(){
// Declare the variables and arrays
int varNum = 1;
int totVar = 0;
int choice = 0;
int userNums[1000] = {};
double ch1 = 0;
double ch2 = 0;
double total = 0;
double avg = 0;
string sym = "";
char dec = 'y';


//Ask the user for their choice and then record it
cout << "6) Guide \n";
cout << "Your choice: ";
cin >> choice;


} else if(choice == 6){
ifstream f("guide.txt");

if (f.is_open())
cout << f.rdbuf();

}
cout << "Would you like to run this program again? (y/n): ";
cin >> dec;
if(dec == 'y') return main();
return 0;
}

最佳答案

我假设您的打印语句类似于:

cout << "guide";
cout << "Would you like to run this program again (y/n):";

如果你想在“guide”和“Would”之间包含一个换行符,你需要做的就是包含一个\n。或使用 endl像这样:

cout << "guide\n";
cout << "Would you like to run this program again (y/n):";

或者替代地

cout << "guide" << endl;
cout << "Would you like to run this program again (y/n):";

编辑:

您需要做的就是 \n就在“你想再次运行这个程序吗(是/否):”之前,它看起来像这样 cout << "\nWould you like to run this program again (y/n):";

关于c++ - 在 C++ 中读取文件时,您如何做到在文件末尾有换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42010777/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com