Home > Back-end >  Inserting multiples values into text file from user input
Inserting multiples values into text file from user input

Time:07-17

I have this project where I need to insert multiples integers into text file by taking user input with certain range of that input in loop

void append_text_multiple() {
    std::string file_name;
    std::cin >> file_name;
        
    std::ofstream getfile;
    getfile.open(("C:\\users\\USER\\Documents\\located_file\\"   file_name  ".txt").c_str());
        
    std::string verify_dtype;
    std::cin >> verify_dtype;
    
    if(verify_dtype == "int" || "INT") {    
        int total_line;
        int item_append;
        std::cin >> total_line;
        for(int j=0; j<=total_line; j  ) {
            std::cin >> item_append;
            getfile << item_append << '\n\';
            getfile.close();
        }
    }
}

Now that when I inserted 1 2 3 4 5 as my input while being inside the loop the output of that text file returns only single value which is 1 while I was expecting for 1 2 3 4 5. I'm not sure what's going on?

CodePudding user response:

There are several issues in your code:

  1. Your for loop does total_line 1 iterations, instead of total_line. The loop should be for(int j=0; j<total_line; j ) (< instead of <=).
  2. You close the output file immediatly after writing the first value. Therefore the later writes are not performed. You should close it after all the values are written.
  3. Your condition for checking the value of verify_dtype is wrong, assuming you wanted to check whether the varaible has either 1 of the 2 values.

Fixed version:

#include <iostream>
#include <fstream>

void append_text_multiple() {
    std::string file_name;
    std::cin >> file_name;

    std::ofstream getfile;
    getfile.open(("C:\\users\\USER\\Documents\\located_file\\"   file_name   ".txt").c_str());

    std::string verify_dtype;
    std::cin >> verify_dtype;
    
    if ((verify_dtype == "int") || (verify_dtype == "INT")) {
        int total_line;
        int item_append;
        std::cin >> total_line;
        for (int j = 0; j < total_line; j  ) {
            std::cin >> item_append;
            getfile << item_append << "\n";
        }
        getfile.close();
    }
}

int main() {
    append_text_multiple();
}
  •  Tags:  
  • c
  • Related