c++ - (C++) 将数组内容写入文件时出现问题

标签 c++ arrays ofstream

学校作业。基本上必须为驾驶员考试创建一个测试 key ,然后验证学生是否通过了考试。正确答案将存储在一个数组中,学生的答案和全名将根据用户输入存储在另一个数组中,并写入文本文件。

有一段时间我认为我所做的是正确的,直到我去运行程序并注意到无论数组的长度有多长,它都会写一个奇怪的 I 字符,上面有一个重音符号。它还将数组的正确答案写入我不想做的文件。我需要写入文件的是:(全名、学生答案 (20)、全名、​​学生答案 (20) 等。)

由于某种原因,文件的首字母也被截断了。 (例如“John Doe”变成“ohn Doe”)这个错误的原因是什么?如果没有 cin.ignore() 语句,我不确定如何将我需要的全名放入文件中。

我已将顶部的数组大小设置为常量,允许我将其更改为 4 个空格而不是 20 个以进行快速测试。

感谢任何帮助。非常新的编程。到目前为止享受它只是有时会遇到困难。

我的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void Correct_Answers(const int SIZE, char correctAnswers[]);
void Submitted_Answers(const int SIZE, char submittedAnswers[]);
void Get_Name(string &fullName);



int main()
{
    const int SIZE = 4;
    char correctAnswers[SIZE];
    char submittedAnswers[SIZE];
    string fileName;
    string fullName;
    char go = 'Y';
    ofstream outputObj;

    Correct_Answers(SIZE, correctAnswers);

    cout << "\nEnter the file name: ";
    cin.ignore();
    getline(cin, fileName);
    outputObj.open(fileName);


    while (go == 'Y' || go == 'y')
    {
        Get_Name(fullName);
        outputObj << fullName << endl;

        Submitted_Answers(SIZE, submittedAnswers);
        outputObj << submittedAnswers << endl;

        cout << "\nTo process another user enter Y. To quit enter N: ";
        cin >> go;
    }


    cout << "\n\n\n";
    system("Pause");
    return(0);
}

void Correct_Answers(const int SIZE, char correctAnswers[])
{
    int questionCounter = 0;

    cout << "\nEnter the correct answers for the drivers exam.\n";

    for (int x = 0; x < SIZE; x++)
    {
        cout << "\tQuestion #" << ++questionCounter << ": ";
        cin >> correctAnswers[x];
        while (correctAnswers[x] != 'A' && correctAnswers[x] != 'a' && correctAnswers[x] != 'B' && correctAnswers[x] != 'b' && correctAnswers[x] != 'C' && correctAnswers[x] != 'c' && correctAnswers[x] != 'D' && correctAnswers[x] != 'd' )
        {
            cout << "\tInvalid entry. Re-enter answer: ";
            cin >> correctAnswers[x];
        }
    }
}

void Submitted_Answers(const int SIZE, char submittedAnswers[])
{
    int questionCounter = 0;

    cout << "\nWelcome to the written portion of the drivers exam!";
    cout << "\nDo your best to answer the questions to the best of your knowledge.";
    cout << "\n15 out of 20 are needed to pass the exam. Best of luck!\n\n";

    for (int x = 0; x < SIZE; x++)
    {
        cout << "\tQuestion #" << ++questionCounter << ": ";
        cin >> submittedAnswers[x];
        while (submittedAnswers[x] != 'A' && submittedAnswers[x] != 'a' && submittedAnswers[x] != 'B' && submittedAnswers[x] != 'b' && submittedAnswers[x] != 'C' && submittedAnswers[x] != 'c' && submittedAnswers[x] != 'D' && submittedAnswers[x] != 'd')
        {
            cout << "\tInvalid. Re-enter answer: ";
            cin >> submittedAnswers[x];
        }

    }

}

void Get_Name(string &fullName)
{
    cout << "\nEnter the users name: ";
    cin.ignore();
    getline(cin, fullName);
}

最佳答案

当你写入文件时你变得垃圾的原因是当你在文件上使用 >> 运算符时,ofstream 对象,你实际上是在向它传递一个指针,它只是不断读取字符直到它找到行尾或空格。例如:

int main()
{
    char submittedAnswers[4] = { 'a', 'b', 'c', 'd' };
    char * memptr = submittedAnswers; // Points to "abcdÌÌÌ̤ònÉÈø+="
    ofstream outputObj ("d:/filetest.txt");

    outputObj << submittedAnswers << endl;
}

这就是为什么它将垃圾打印到文件中的原因。

您丢失“John Doe”首字母的原因是:

cin.ignore(); // This discards the first character.
getline(cin, fullName);

那你为什么要做 cin.ignore()?因为你认为你必须在阅读一行之前添加 cin.ignore() 才能工作:

cout << "\nEnter the file name: ";
cin.ignore(); // You've added this because otherwise getline(cin, fileName)
              // ends up empty
getline(cin, fileName);
outputObj.open(fileName);

如果省略 cin.ignore(),为什么 getline() 会返回一个空字符串?因为你调用的时候cin缓冲区里面还有一个'\n'换行符。

当你回答你的问题时:

cin >> correctAnswers[x]; 

在循环中。每当该行执行时,默认情况下都会跳过空格和新行。当您输入答案时,您会输入一些内容,然后按回车键。当您按下回车键时,它会向缓冲区添加一个“\n”。所以命令行输入被插入到 correctAnswers[] 中,但是在最后一个 cin >> 中,你在它的末尾有一个 '\n' 字符,这就是为什么你必须在调用 getline() 之前调用 cin.ignore , 以跳过缓冲区中的这个 '\n' 字符。

关于c++ - (C++) 将数组内容写入文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426533/

相关文章:

c++ - 查找字符串 C++ 中重复字符串的总数——没有映射

c++ - clang6 实现 std::可选 吗?

c# - 如何将 float 组从 C# 复制到 C dll

c++ - ofstream重置精度

c++ - std::ofstream 打开的 klocwork 问题

c++ - 未找到 stdarg.h

c++ - C++17是基于C17的吗?

javascript - 如何通过对象数组中的键值合并或连接数据?

arrays - Ruby:禁止更新作为类变量的数组

c++ - 连接 const char* C++