Question

In: Computer Science

C++ question. I want to write all output to the file "output.txt", but it will write...

C++ question.

I want to write all output to the file "output.txt", but it will write just first character. Can you fix it?

#include

#include

#include

#include

#include

using namespace std;

using std::cin;

using std::cout;

using std::string;

// remove dashes convert letters to upper case

string normalize(const string &isbn) {

string ch;

for (char i : isbn) {

if (i == '-') {

continue; // if "-" then skip it

}

  

if (isalpha(i)) {

i = toupper(i); // Check uppercase

}

ch += i;

}

return ch;

}

// return the number of digits in to the string

size_t numDigits(string &str) {

size_t numDigits = 0;

for (char ch : str) {

if (isdigit(ch)) {

++numDigits;

}

}

return numDigits;

}

enum ValidationCode {

Ok, // validation passed

NumDigits, // wrong number of digits

ExtraChars,// extra characters in isbn

Done

};

enum ValidationCode validate(string &isbn) {

int Done = 4;

string normal = normalize(isbn);

size_t count = numDigits(normal);

if (normal.size() == Done)

exit(0);

if (count != 10) {

return NumDigits;

}

  

if (normal.size() == 10 || normal.size() == 11 && normal[10] == 'X') {

return Ok;

}

return ExtraChars;

}

int main() {

// open a file

ofstream file("output.txt");

//The following code is taken from (https://en.cppreference.com/w/cpp/io/basic_ios/fail)

// check if the file can open

if(!file) // operator! is used here

{

std::cout << "File opening failed\n";

return EXIT_FAILURE;

} //end of borrowed code

  

// read a file

//The following code is referenced from (https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c)

std::ifstream ifs("test_data.txt");

// check if the file can read

if (ifs.fail())

{

std::cerr << "test_data.txt could not read" << std::endl;

return -1;

} //end of referenced code

std::string str;

while (ifs >> str){

switch (validate(str)) {

case Ok:

cout << str << " is a valid isbn\n";

file << str << " is a valid isbn\n";

break;

case NumDigits:

cout << str << " doesn't have 10 digits\n";

file << str << " doesn't have 10 digits\n";

break;

case ExtraChars:

cout << str << " has extra characters\n";

file << str << " has extra characters\n";

break;

default:

cout << "ERROR: validate(" << str << ") return an unknown status\n";

file << "ERROR: validate(" << str << ") return an unknown status\n";

break;

}

}

ifs.close();

file.close();

}

test_data.txt

1-214-02031-3
0-070-21604-5
2-14-241242-4
2-120-12311-x
0-534-95207-x
2-034-00312-2
1-013-10201-2
2-142-1223
3-001-0000a-4
done

Solutions

Expert Solution

/* the problem was buffer got full to clear it we have to use flush method */

/* Run code it's working now*/

#include<iostream>

#include<fstream>

using namespace std;

// remove dashes convert letters to upper case

string normalize(const string &isbn) {

string ch;

for (char i : isbn) {

if (i == '-') {

continue; // if "-" then skip it

}

  

if (isalpha(i)) {

i = toupper(i); // Check uppercase

}

ch += i;

}

return ch;

}

// return the number of digits in to the string

size_t numDigits(string &str) {

size_t numDigits = 0;

for (char ch : str) {

if (isdigit(ch)) {

++numDigits;

}

}

return numDigits;

}

enum ValidationCode {

Ok, // validation passed

NumDigits, // wrong number of digits

ExtraChars,// extra characters in isbn

Done

};

enum ValidationCode validate(string &isbn) {

int Done = 4;

string normal = normalize(isbn);

size_t count = numDigits(normal);

if (normal.size() == Done)

exit(0);

if (count != 10) {

return NumDigits;

}

  

if (normal.size() == 10 || normal.size() == 11 && normal[10] == 'X') {

return Ok;

}

return ExtraChars;

}

int main() {
  
   // open a file
  
   ofstream file("output.txt");


  
   if(!file) // operator! is used here
  
   {
  
   std::cout << "File opening failed\n";
  
   return EXIT_FAILURE;
  
   } //end of borrowed code
      
  
   ifstream ifs("test_data.txt");
  
   // check if the file can read
  
   if (ifs.fail())
  
   {
  
   std::cerr << "test_data.txt could not read" << std::endl;
  
   return -1;
  
   } //end of referenced code
  
   string str;

  
   while (ifs >> str){

   switch (validate(str)) {
  
       case Ok:
               cout << str << " is a valid isbn\n";
               file << str << " is a valid isbn\n";
           break;  
       case NumDigits:
      
               cout << str << " doesn't have 10 digits\n";
               file << str << " doesn't have 10 digits\n";
      
           break;
      
       case ExtraChars:
      
           cout << str << " has extra characters\n";
          
           file << str << " has extra characters\n";
          
           break;
  
       default:
  
           cout << "ERROR: validate(" << str << ") return an unknown status\n";
  
           file << "ERROR: validate(" << str << ") return an unknown status\n";
  
           break;
  
       }
       file.flush(); // to clear buffer
   }
  
   ifs.close();
  
   file.close();

}  

/* PLEASE UPVOTE */

/* OUTPUT */


Related Solutions

C Programming: Write a program that accepts 2 arguments, an input file and an output file....
C Programming: Write a program that accepts 2 arguments, an input file and an output file. The program is to store in the output file the contents of the input file in reverse. If the input file looks like this: Hello World.\n This is Line 2\n This is the end.\n then the output file should look like this: \n .dne eht si sihT\n 2 eniL si sihT\n .dlroW olleH The main program should look like this: int main(int argc, char...
For c language. I want to read a text file called input.txt for example, the file...
For c language. I want to read a text file called input.txt for example, the file has the form. 4 hello goodbye hihi goodnight where the first number indicates the n number of words while other words are separated by newlines. I want to store these words into a 2D array so I can further work on these. and there are fewer words in the word file than specified by the number in the first line of the file, then...
In C Programming Language Write a program to output to a text log file a new...
In C Programming Language Write a program to output to a text log file a new line starting with day time date followed by the message "SUCCESSFUL". Please screenshot the results.
Using C++, write a code that this program always stores text file output into a text...
Using C++, write a code that this program always stores text file output into a text file named "clean.txt". -The program should read one character at a time from "someNumbers.txt", and do the following. -If it is a letter, print that letter to the screen, AND also store it in the text file. All letters should be converted to lowercase beforehand. -If it is a number, print that number to screen, but do NOT store it in the text file....
modify code to write the output as an HTML table to a file in the output...
modify code to write the output as an HTML table to a file in the output directory. The file that is saying to work at : SOURCE CODE IN PERL: print "Enter principal amount: "; $P=; while($P<=0) { print "Principal must be positive. Try again: "; $P=; } print "Enter number of times interest is applied in a year: "; $n=; while($n!=12 && $n!=4 && $n!=2 && $n!=1) { print "It must be 12, 4, 2 or 1. Try again:...
C++ i want .00 at the output cout << fixed << setprecision (2);where should i put...
C++ i want .00 at the output cout << fixed << setprecision (2);where should i put this line? quesstion 13. Array of Payroll Objects Design a PayRoll class that has data members for an employee’s hourly pay rate and number of hours worked. Write a program with an array of seven PayRoll objects. The program should read the number of hours each employee worked and their hourly pay rate from a file and call class functions to store this information...
c# code working but output not right, I need to output all numbers like : Prime...
c# code working but output not right, I need to output all numbers like : Prime factors of 4 are: 2 x 2 here is just 2 Prime factors of 7 are: 7 Prime factors of 30 are: 2 x 3 x 5 Prime factors of 40 are: 2 x 2 x 2 x 5 here is just 2,5 Prime factors of 50 are: 2 x 5 x 5 here is just 2,5 1) How I can fix it 2)I...
Write a program that creates an output file named rand_nums.txt. Open the file and write 100...
Write a program that creates an output file named rand_nums.txt. Open the file and write 100 random integers between -50 and +50 (inclusive) to the file. Be sure to handle any file IO exceptions. Remember to close the file. Write a program that opens rand_nums.txt for input. Create two output files pos.txt and neg.txt. Read through the input file, one line at a time, converting each line into an integer (no exception handling, yet). If the number is positive, write...
I want the program to use 1- D array and display a table as output. Write...
I want the program to use 1- D array and display a table as output. Write a script to simulate the rolling of two dice. The script should use Math.random to roll the first die and again to roll the second die. The sum of the two values should then be calculated. [Note: Since each die can show an integer value from 1 to 6, the sum of the values will vary from 2 to 12, with 7 being the...
Please in C++, show screenshots of output plus .txt file. thanks Breakfast Billing System Write a...
Please in C++, show screenshots of output plus .txt file. thanks Breakfast Billing System Write a program to help a local restaurant automate its breakfast billing system. The program should do the following: Show the customer the different breakfast items offered by the restaurant. Allow the customer to select more than one item from the menu. Calculate and print the bill Assume that the restaurant offers the following breakfast items (the price of each item is shown to the right...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT