C++ reading command from .txt file - c++

I want to create a little "calculator" but I dont know how can I create.
My problem is, I have an input file (.txt) with codes:
acc +40
acc -14
nop +386
jmp +262
acc -4
nop +25
...
the "acc" adds the number to my variable
the "jmp" is jump to the line (jmp +500 jump foward 500 line)
the "nop" dont do anything
and here is my code but not working (the acc is okay, but the jmp is not)
ifstream file("my.txt");
string cmd;
int num;
int var= 0;
int i = 0;
if(file.is_open())
{
while (file >> cmd >> num)
{
cout << "Var" << var<< endl;
cout << "Command: " << cmd << " Number: " << num<< " ----" << i <<" // Var: " << var<< endl;
++i;
if(cmd == "acc")
{
var= var+ num;
}
if(cmd == "jmp")
{
;
}
}
file.close();
}else {
cout << "error"<< endl;
cin.get();
}

This is a sample code. I hope everything here is in order. I did what Some programmer dude told you. Using vectors, you read all the lines into them and then just iterate.
#include <fstream>
#include <iostream>
#include <string> //addition
#include <vector> //addition
using namespace std;
int main() {
ifstream file("my.txt");
string cmd;
int num;
int var= 0;
int i = 0;
string my_string;//addition
vector<int> numbers;//addition
vector<string> commands;//addition
if(file.is_open())
{
/*this while function reads every line of the file and writes command to the vector of strings named "commands" and the number to the vector of integers named "numbers".*/
while (getline(file, my_string))//while you can read line from "file", read it and put in into string called "my_string".
{
cmd = my_string;
cmd.resize(3);//leaves only first three characters of the string.
commands.push_back(cmd);//adds this "cmd" string to vector "commands"
my_string.erase(0,4);//erases characters from 0 to 4, inclusive, from the string "my_string". So erases first 4 characters, so our command and the space after.
numbers.push_back(stoi(my_string));//adds my_string, converted to int, to vector "numbers". Stoi() converts string to int.
++i;
}
for(i = 0; i < commands.size(); i++)
{
cout << "Var " << var << endl;
if(commands[i] == "acc")
{
//remember about "+=", it's quicker this way :)
var += numbers[i];
}
cout << "Command: " << commands[i] << " Number: " << numbers[i] << " ----" << i <<" // Var: " << var << endl;
if(commands[i] == "jmp")
{
i+= numbers[i];
}
}
file.close();
}else {
cout << "error"<< endl;
cin.get();
}
}
Sorry in advance for any formatting issues. My first answer on stackoverflow...

Related

C++ UTF-8 Reading text file, counting characters and outputing results to another file. ‘ gets saved as nothing, but is counted. ā and € appears

I have a task in C++ to read from a UTF-8 text file, count the characters, and save the character + count in a tsv.
I use everywhere wstring, wifstream, and wofstream.
In the terminal, there are many empty spaces when checking everything, but when outputting to tsv everything is overall fine except for 3 things.
‘ when saved appears as nothing, but its amount is counted correctly.
From nowhere ā and € appear. They are counted as the same amount, but they are not present in the original text at all.
What might be the cause of these issues?
The code is a bit crude but looks like this currently
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector <wchar_t> characters;
vector <int> counter;
string filename;
string param;
cout << "Please input the filename: ";
cin >> filename;
cout << "Please, if you want to convert everything to lowercase, input 'lower', else input 'No': ";
cin >> param;
wifstream inFile;
wofstream endFile("dancing_men_char_frequency.tsv");
inFile.open(filename);
wstring Tfile;
int checker;
//inFile >> Tfile;
while(getline(inFile, Tfile)) {
//wcout << Tfile;
//sort(Tfile.begin(), Tfile.end());
if(param == "lower"){
transform(
Tfile.begin(), Tfile.end(),
Tfile.begin(),
towlower);
}
for(int i = 0; i < Tfile.length(); i++){
if(find(characters.begin(), characters.end(), Tfile[i]) != characters.end())
{
if(isblank(Tfile[i])){}else{
checker = 0;
while(characters[checker] != Tfile[i]){
checker++;
}
counter[checker] += 1;
}
}else{
if(isblank(Tfile[i])){}else{
characters.push_back(Tfile[i]);
counter.push_back(1);
}
}
}
}
int sum = 0;
for(int i = 0; i < characters.size(); i++){
wcout << characters[i] << " ";
cout << counter[i] << " " << i << endl;
sum += counter[i];
endFile << characters[i] << '\t' << counter[i] << '\n';
}
cout << sum << endl;
//wcout << Tfile;
//sort(Tfile.begin(), Tfile.end());
//wcout << Tfile;
endFile.close();
inFile.close();
return 0;
}

How do I replace a specific word within a line in a file?

My Text File:
Name G M S
Cart 1 0 1
Jane 0 1 0
What I have so far:
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
void scoreChanger();
string line;
int main()
{
string yn;
int ctr = 0;
ifstream infile;
infile.open("WiiTourney.txt");
if (infile.is_open())
{
cout << "This is your current score table: " << endl;
while(getline(infile, line))
{
ctr++;
cout << line << endl;
cout << ctr << endl;
}
cout << endl;
}
else
{
cout << "Unable to open file" << endl;
}
infile.close();
cout << endl;
cout << "Would you like to change the scores? " << endl;
cin >> yn;
transform(yn.begin(), yn.end(), yn.begin(), ::tolower);
if (yn == "yes")
{
scoreChanger();
}
else
{
infile.close();
return 0;
}
return 0;
}
void scoreChanger()
{
string name;
ofstream outfile;
outfile.open("WiiTourney.txt");
if (outfile.is_open())
{
cout << "Who won the game? " << endl;
cin >> name;
transform(name.begin(), name.end(), name.begin(), ::tolower);
if (name == "jane")
{
while(getline(outfile, line))
{
cout << line << endl;
}
}
for (int x = 0; x < line.length(); x++)
{
if (line[x] == 8 && line[x] != 'G')
{
}
}
}
else
{
cout << "Error opening file. " << endl;
exit(1);
}
}
What I want it to do:
Let's say I wanted to be able to add 1 point to the Games column(G) only for Cart. The problem for me is that I only want to change the 1 in the G column and I know that I would encounter problems by just looping through and searching for instances where 1 comes up because there could be multiple 1's in one line. I am also getting the error on the line while(getline(outfile, line)) that says "no matching function for call to 'getline(std::ofstream&, std::string&)'"
Thank you, your help is very much appreciated.
My first thought was that the structure of the table is very uniform, so you could determine the position of a specific score using columns and rows.
Because the names are the only elements with variable length (assuming the scores don't go above 9, because that would give 2 characters), I would first read the first word of every row and input this into an array of names.
From this you can find specific elements using the row and column indices. If C++ doesn't contain a function to get characters based on row and column indices, I would loop through the file and add each character to the corresponding position in a 2-dimensional array.
For example:
characters[0][0]
would return N, from the start of "Names".
And of course to retrieve the score you incorporate the length of the name the specific line to get the value:
characters[names[0].length()+1][1]
This would return the score under G for the first name in the list.

get string array from text list c++

my text file was like
123456123456
Jason
uk
012456788
1000
456789456789
david
uk
012456788
1000
i'm trying to get the data from a text file and save it into arrays
however when i want to store the data from the text file into array it loop non-stop.
what should i do ?
the problem exiting in looping or the method i get the data from text file ?
code:
#include <iostream>
#include <fstream>
using namespace std;
typedef struct {
char acc_no[12];
char name[30];
char address[50];
char phone_no[12];
double balance;
} ACCOUNT;
//function prototype
void menu();
void read_data(ACCOUNT record[]);
int main() {
ACCOUNT record[31]; //Define array 'record' which have maximum size of 30
read_data(record);
}
//--------------------------------------------------------------------
void read_data(ACCOUNT record[]) {
ifstream openfile("list.txt"); //open text file
if (!openfile) {
cout << "Error opening input file\n";
return 0;
} else {
int loop = -1; //size of array
cout << "--------------Data From File--------------"<<endl;
while (!openfile.eof()) {
if (openfile.peek() == '\n')
openfile.ignore(256, '\n');
openfile.getline(record[++loop].acc_no, 12);
openfile.getline(record[loop].name, 30);
openfile.getline(record[loop].address, 50);
openfile.getline(record[loop].phone_no, 12);
openfile >> record[loop].balance;
}
openfile.close(); //close text file
for (int i = 0; i <= loop + 1; i++) {
cout << "Account " << endl;
cout << "Account No. : " << record[i].acc_no << endl;
cout << "Name : " << record[i].name << endl;
cout << "Address : " << record[i].address << endl;
cout << "Phone Number : " << record[i].phone_no << endl;
cout << "Balance : " << record[i].balance << endl;
}
}
}
UPDATE:
The OP didn't properly cite the correct format in his data file. This answer is only valid up until the last iteration.
Don't use .eof() - that's more applicable to when you want to open the file and read it by characters.
A better way would be to use the insertion operator >> as follows:
#define ARR_SIZE 31
ACCOUNT temp;
ACCOUNT record[ARR_SIZE];
int i=0;
while(i < ARR_SIZE) {
openfile >> temp.acc_no >> temp.name >> temp.address >> temp.phone_no >> temp.balance;
record[i] = temp;
i++;
}
Of course, even better is to use std::string to hold the values from the input file, in addition to using std::vectors instead of arrays.

C++ iteration, file i/o

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
int main()
{
//Input .txt file
ifstream inputFile ("input.txt");
try
{
int i = 1; //Line iterator
int vertices = 0;
int faces = 0;
string line;
while (getline(inputFile, line))
{
//Take number from line 4, set as variable "vertices"
if (i == 3)
{
getline (inputFile,line);
size_t last_index = line.find_last_not_of("0123456789");
string str = line.substr(last_index);
vertices = atoi(str.c_str()); //Convert to int
cout << "vertices " + str << endl;
}
//Take number from line 11, set as variable "triangles"
if (i == 11)
{
getline (inputFile,line);
size_t last_index = line.find_last_not_of("0123456789");
string str = line.substr(last_index);
faces = atoi(str.c_str()); //Convert to int
cout << "faces " + str << endl;
}
if (i == 13)
{
i++;
break;
}
cout << "line: " + i << endl; //Prints line number
i++;
}
} catch(const char* error) {
cout << "Cannot read file, please try again." << error;
}
return 0;
}
This program is simply trying to read file, take a number from a couple of lines and for each line print "line: " with respective line number. It looks like C++ iterates differently to Java?
For some reason this program outputs:
*ine:
ne:
vertices 752
e:
:
Cannot read mesh, please try again.
faces r
annot read mesh, please try again.
nnot read mesh, please try again.*
I have no idea why.
This line:
cout << "line: " + i << endl;
should be:
cout << "line: " << i << endl;
Your + is adding i to the string constant "line: ", which has the effect of knocking one character off the front each time round the loop (and eventually going off the end, leading to undefined behaviour).
You can't add objects to strings in C++ in the way you're attempting, but you can send multiple objects to cout by repeated use of <<.
You then have the same problem here:
cout << "vertices " + str << endl;
and here:
cout << "faces " + str << endl;

File pointer movement for getline

I have got an input file with following data
2
100
2
10 90
150
3
70 10 80
Now, I am able to read till 4th line ( 10 90) but when reading 5th line(150), the file pointer seems to be stuck at 4th line. I have tried infile.clear() just incase. How do I make sure that file pointer is moving correctly or position it at next line? Appreciate your feedback.
-Amit
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(void) {
int cases;
int total_credit=0;
int list_size=0;
string list_price;
//Read file "filename".
ifstream infile;
infile.open("A-large-practice.in",ifstream::in);
if(!infile.is_open()) {
cout << "\n The file cannot be opened" << endl;
return 1;
}
else {
cout<<"Reading from the file"<<endl;
infile >> cases;
cout << "Total Cases = " << cases << endl;
int j=0;
while (infile.good() && j < cases) {
total_credit=0;
list_size=0;
infile >> total_credit;
infile >> list_size;
cout << "Total Credit = " << total_credit << endl;
cout << "List Size = " << list_size << endl;
//cout << "Sum of total_credit and list_size" << sum_test << endl;
int array[list_size];
int i =0;
while(i < list_size) {
istringstream stream1;
string s;
getline(infile,s,' ');
stream1.str(s);
stream1 >> array[i];
//cout << "Here's what in file = " << s <<endl;
//array[i]=s;
i++;
}
cout << "List Price = " << array[0] << " Next = " << array[1] << endl;
int sum = array[0] + array[1];
cout << "Sum Total = " << sum << endl;
cout <<"Testing" << endl;
j++;
}
}
return 0;
}
The problem is that you're using ' ' (space) as your "line terminator" for getline. So when you're reading the numbers on line 4 into the string s, the first one will be "10" and the second will be "90\n150\n3\n70" -- that is, everything up to the next space. This is almost certinaly not what you want and is leading to your confusion about where you are in the file. The next number you read will be 10, leading you to think you're on line 4 when in fact you're on line 7.
edit
The easiest way to fix this is probably to not use getline at all and just read ints directly from the input:
while (i < list_size)
infile >> array[i++];
This ignores the newlines altogether, so the input might as well be all on one line or split between lines randomly, but as you have an initial number that tells you how many numbers to read, that's just fine.