not very good at coding yet, and I am doing a c program that needs to read txt file and take line-by-line string input and iterate it through the program. each line has 18 numbers. It reads the lines but only cycles the last line. I need it to run all lines through the equation, so I can verify the checksum of each using the order set and weight with modulo 11. That part is fine, and it is working. This is the main part of the program. did not include all 200 lines as they are just switch if else and some conversions. if needed, I can upload it all.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
stringstream cs;
stringstream ss;
stringstream rr;
stringstream mm;
string input;
//This is for manual inputs
//cout << "Enter 18 digit number: ";
//cin >> input;
std::ifstream File ("idnumbers.txt");
//Checking the file opening condition
if (File.is_open())
{
while (std::getline (File,input))
{
cout << input << '\n';
}
File.close();
}
if (input.length() != 18)
{
cout << "Length of ID is incorrect." << endl;
return 1;
}
int orderedSet[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
string index = "10X98765432";
int sum = 0;
for (int i = 0; i < 17; i )
{
sum = (input[i] - '0') * orderedSet[i];
}
CodePudding user response:
First of all you have to understand what is the use of the instruction using namespace std; Because you don't need to put std:: before the getline() for example.
It's normal that your code treats only the last line of your text file because it's this line that you store last before closing the file. If you want to continue with your blocks as they are, you will have to use a container (a vector for example to store all the lines). But that would be complicating your life for nothing. To make it simpler, with your same code, you can just do this:
ifstream File ("idnumbers.txt");
//Checking the file opening condition
if (File)
{
while (getline (File,input)) //We read all lines
{
cout << input << endl;
if (input.length() != 18)
{
cout << "Length of ID is incorrect." << endl;
return 1;
}
int orderedSet[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
string index = "10X98765432";
int sum = 0;
for (int i = 0; i < 17; i )
{
sum = (input[i] - '0') * orderedSet[i];
}
}
File.close();
}
- There are variables in your code that are not used. For example, sum is not used because you don't use it.
NB: I have not tested this code and it is yours. I just moved some blocks following the logic. Soory for my poor english.