c++ - 尝试将多个输出写入 .txt 文件 C++

标签 c++ io

我想将 inputtwo.h 中的内容输出到 txt 文档中。该文件可以很好地命名。但是当我按要求输入时,txt 中的返回是一行文本,但格式错误

所以说我做了两个输入,命名为test.txt,然后输入“dog cat”,然后txt中的输出是“dogcatcatdog”,它应该是 “狗” “猫” “狗猫” “猫狗” 每个都应该在 txt 中的自己的行上

以下代码是我的主文件

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() 
{
char q1[20];
char q2[20];

int x;

printf("Select number of keywords (integer between 1-10): \n");
scanf("%d", &x);

switch(x){

    case 1:{
        string fileName;
    printf("Input Filename\n");
    cin >> fileName;
    fileName += ".txt";
    ofstream createFile;
    createFile.open(fileName.c_str(), ios::app);

    printf("Input One Keywords: \n");
    scanf("%s", q1);
    createFile << ("%s\n", q1);
    createFile.close();
    return 0;
}
    case 2:{
        string fileName2;
    printf("Input Filename\n");
    cin >> fileName2;
    fileName2 += ".txt";
    ofstream createFile;
    createFile.open(fileName2.c_str(), ios::app);

    printf("Input Two Keywords: \n");
    scanf("%s %s", q1, q2);
#include "inputtwo.h"
    createFile.close();
    return 0;
} 

include inputtwo.h 是

#ifndef INPUTTWO_H
#define INPUTTWO_H

    createFile << ("%s\n", q1);
    createFile << ("%s\n", q2);
    createFile << ("%s" "%s\n", q1, q2);
    createFile << ("%s" "%s\n", q2, q1);

#endif /* INPUTTWO_H */

最佳答案

在 inputtwo.h 中,您正在使用 C++ 输出(文件)流写入文件,它不理解“%s\n”形式的格式说明符。 ("%s\n", q1) 是一个表达式,其中逗号 , 是一个运算符(参见 this)。此运算符的结果将是 q1,并将其写入输出流(文件)。

总体结果是,您编写的 q1、q2、q1、q2、q2 和 q1 之间没有任何分隔符。

要解决此问题,请停止混合使用 C 和 C++ 样式的输出。像这样使用 C++ 风格:

createFile << q1 << std::endl;
createFile << q2 << std::endl;  
createFile << q1 << " " << q2 << std::endl;
createFile << q2 << " " << q1 << std::endl;

将其扩展到程序的其余部分,将替换 char q1[20];std::string q1;(与 q2 相同),然后替换

printf("Input One Keywords: \n");
scanf("%s", q1);

std::cout << "Input One Keyword: " << std::endl;
std::cin >> q1;

关于c++ - 尝试将多个输出写入 .txt 文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836325/

相关文章:

c++ - 为什么会出现此错误?无法从 <brace-enclosed initializer list> 转换为 'std::vector<>'

c++ - 插件和基类构造函数

c++ - 通用 Windows 平台 - CustomHidDevice(错误 : Value is blocked)

c# - "FilterByItems"任务意外失败。 Azure Web应用程序发布

c - 使用 fgets 和 strtok 从文件中读取和解析行

c++ - 使用 Eclipse CDT 运行 "dynamic"参数

C++ 对象引用/访问

c - epoll_ctl : Operation not permitted error - c program

c - 使用 sigaction() 进行 I/O 处理

c# - 为什么换行符不起作用?