Loading Variable from a file - c++

AT
4
5
6
7
#include<iostream>
#include<stdio.h>
#include <fstream>
using namespace std;
int main()
{
int data[4], a, b, c, d, e, f;
ifstream myfile;
myfile.open("tera.txt");
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
}
myfile.close();
a = data[0];
b = data[1];
c = data[2];
d = data[3];
cout << a << "\t" << b << "\t" << c << "\t" << d << "\n";
return 0;
}
it takes AT also and give garbage value. how and where should i use ignore function to ignore AT Value.
And there is one thing more if there is another array given BT containing some value like this:
AT BT
how to store BT's all values under it in an array?

You just have to skip the first line. You can also add optional error handling, otherwise read may fail for all line.
if (!myfile)
{
cout << "can't open\n";
return 0;
}
string temp;
myfile >> temp;
cout << "first line: " << temp << endl;
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
if (myfile.fail())
{
cout << "error\n";
myfile.clear();
myfile.ignore(1000000, '\n');
}
}

Related

I want this c++ program to find the the words starting with user entereed letter and print them using a new function

I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}

Adding conditions to a conditional statement

I am messing around with dynamic arrays for a user defined amount of inputs for an and gate.
The issue I am running into is that I don't know how many inputs the user is going to test and I need to be able to have an if-else statement that tests each input.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput = 0;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1 = 0;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
return 0;
}
Here is the code that I am currently trying to find a solution for.
To implement an AND gate with n inputs you can simply do:
int output = 1;
for (int i = 0; i < n; ++i)
{
if (!and_gate [i])
{
output = 0;
break;
}
}
// ...
Use Vector data structure, you don't need to tell its size while declaring, unlike array, and it can grow automatically.
To read input till it's arriving, put cin inside while loop condition. I used getline to read whole line and work with it, so that whenever user presses enter button at empty line, program will think that no more input is coming anymore, and will start calculating 'And' of inputs.
//don't forget to import vector
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
logic_gate(){ //default constructor
}
logic_gate(int k){ //another constructor needed
x = k;
}
};
int main(){
cout << endl << "Please enter the values of each bit below . . ." << endl;
vector<logic_gate> and_gate; //no need to tell size while declaration
string b;
while(getline(cin, b)){ //read whole line from standard input
if (b == "\0") //input is NULL
break;
and_gate.push_back(logic_gate(stoi(b))); //to convert string to integer
}
if (!and_gate.empty()){
int output = and_gate[0].x;
for (int i = 1; i < and_gate.size(); i++){
output = output & and_gate[i].x;
}
cout << "And of inputs is: " << output << endl;
}
else{
cout << "No input was given!\n";
}
return 0;
}
Feel free to ask if some doubts linger
I figured out what I wanted to do. Thanks to everyone who helped and especially Paul Sanders. Below is my final code.
#include <iostream>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput;
int output = 1;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
if (userInput == 1) {
output = userTest1;
cout << "The test of " << userTest1 << " is " << output << endl << endl;
}
else if (userInput > 1) {
for (int i = 0; i < userInput; i++) {
if (!and_gate[i].x)
{
output = 0;
break;
}
}
cout << "The test of ";
for (int i = 0; i < userInput; i++) {
cout << and_gate[i].x;
}
cout << " is " << output << endl << endl;
}
return 0;
}

How to get multiple line in a loop from a file?

I want to get multiple lines sequentially from a file and then save them to a variable. If in Java can be using scanner.nextInt.
How about C++?
int main(){
string line;
int a, b, c;
ifstream myFile("input.in");
if(myFile.is_open()){
while(getline(myFile,line)){
int cases = atoi(line.c_str());
double count[cases];
cout << "cases : "<<cases << "\n";
for(int i = 1; i <= cases; i++){
a = atoi(line.c_str());
b = atoi(line.c_str());
c = atoi(line.c_str());
cout << a << b << c;
}
}
}
return 0;
}
You can use while(input.in >> cases) to read the next int into cases until end of file (EOF) is reached. I've updated your code below.
int main(){
string line;
int a, b, c;
ifstream myFile("input.in");
if(myFile.is_open()) {
int cases = 0;
while(myFile >> cases) { // breaks on eof
double count[cases];
cout << "cases : " << cases << "\n";
for(int i = 1; i <= cases; i++){
myFile >> a;
myFile >> b;
myFile >> c;
cout << a << b << c;
}
}
}
return 0;
}

C++ Mastermind For Loop

Edit
I've included #include <sstream> now. This helped. But still an issue displaying the correct information. I've stepped it out, and it has to deal with some sort of program error. I have the text file already made inside of the same folder path. I've tried setting it to a direct C:/ path such as
C:\Users\Matt\Documents\Visual Studio 2015\Projects\listofcolors.txt
I'm having problem opening my file and displaying data. I recently downloaded Microsoft Visual Basic C++ to write the program I need for Mastermind. My goal is to create numbers that represent 9 to the 5th and put them within a text file. (Essentially, 5 columns of 9 numbers, 9 I've written this so far.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
std::string result;
std::stringstream sstm;
ofstream myfile;
myfile.open("listofcolors.txt");
if (myfile.is_open())
{
for (a = 0; a<9; a++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (b = 0; b<9; b++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (c = 0; c<9; c++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (d = 0; d<9; d++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
for (e = 0; e<9; e++) {
sstm << a << b << c << d << e;
result = sstm.str();
myfile << result << '\n';
}
}
}
}
myfile.close();
return 0;
}
}
else cout << "Unable to open file";
return 0;
}
For some reason, nothing is outputted. Any ideas??? Thank you!!
We can get clever by borrowing this arbitrary base conversion code that will output numbers in base 9 - see the cout version online here:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
using namespace std;
/**
* C++ version 0.4 std::string style "itoa":
* Contributions from Stuart Lowe, Ray-Yuan Sheu,
* Rodrigo de Salvo Braz, Luc Gallant, John Maloney
* and Brian Hunt
*/
std::string itoa(int value, int base) {
std::string buf;
// check that the base if valid
if (base < 2 || base > 16) return buf;
enum { kMaxDigits = 35 };
buf.reserve( kMaxDigits ); // Pre-allocate enough space.
int quotient = value;
// Translating number to string with base:
do {
buf += "0123456789abcdef"[ std::abs( quotient % base ) ];
quotient /= base;
} while ( quotient );
// Append the negative sign
if ( value < 0) buf += '-';
std::reverse( buf.begin(), buf.end() );
return buf;
}
int main() {
ofstream myfile("listofcolors.text");
if (myfile.is_open())
{
for (int i = 0; i <= 9 * 9 * 9 * 9 * 9; i++)
{
// Formats the number to five places, filled with leading zeroes
myfile << setw(5) << setfill('0') << itoa(i, 9) << '\n';
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
Note that the file is created in the working directory; here is how to check and set where it is.
Also note that your code had the myfile.close() inside the first loop, so it would only have printed from 00000 to 08888.
Finally, since you are on Windows, use File Explorer to search for listofcolors.txt, just in case it is being created in an unexpected location.
On Windows, text files have a .txt file extension, not .text. Also, you are creating the file using a relative path, so it will be created in the process's current working directory, which may not be what you are expecting it to be. Always use absolute paths.
Your loop code is unnecessarily complex, it can be simplified to something more like this:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream myfile("C:\\some path\\listofcolors.txt", ios_base::trunc);
if (myfile.is_open())
{
for (int a = 0; a < 9; a++)
for (int b = 0; b < 9; b++)
for (int c = 0; c < 9; c++)
for (int d = 0; d < 9; d++)
for (int e = 0; e < 9; e++) {
if (!(myfile << a << b << c << d << e << '\n')) {
cout << "Unable to write to file";
return 0;
}
}
myfile.close();
cout << "File created";
}
else
cout << "Unable to create file";
return 0;
}

Array with hex values in C++

For the last day I have had some problems with this code. Here I want to upload with a .txt several hexadecimal values and if the sum of the first five numbers is equal to the last number, the code is correct.Then, the method main have to check if the rest methods were succeeded. But I don't know how do this, so I need your help...
#include <iostream>
#include <fstream>
#define FILECODE "file.txt"
#define N_CODE 6
using namespace std;
ifstream file;
void uploadCode(bool& exist, unsigned int longCode, unsigned int code[]);
bool IsValidCode(unsigned int code[]);
void main() {
unsigned int code[N_CODE];
bool exist;
unsigned int longCode=N_CODE;
IsValidCode(code);
if(IsValidCode(code)==true){
uploadCode(exist,longCode,code); //here I have the problem because I don't know how to call the method
cout << "SUCCESS" << endl;
}
else
cout << "FAIL" << endl;
}
void uploadCode(bool& exist, unsigned int longCode, unsigned int code[]) {
int i;
file.open(FILECODE);
if(file){
exist=true;
for(int i=0;i<longCode;i++){
file >> hex >> code[i];
cout << "Number " << i << ": "<< code[i] << endl;
}
cout << "EXIST" << endl;
}
else
cout << "NO EXIST" << endl;
exist=false;
file.close();
}
bool IsValidCode(unsigned int code[]) {
int i;
int sum=0;
for(int i=0; i<N_CODE-1; i++)
sum+=code[i];
cout << "Sum first five numbers: " << sum << endl;
if(sum==code[6])
return true;
else
return false;
return sum;
}
Here's a minimally modified version that does what you want. Of course, much better checks should be done on the return values of your input processing (i.e. - file >> hex >> code[i];) to see if those inputs are actually succeeding or not.
bool uploadCode(unsigned int longCode, unsigned int code[])
{
bool ret;
file.open(FILECODE); // TODO: no need for a global here; just use a locally constructed ifstream
if (file.good())
{
ret = true;
for(int i = 0; i < longCode; ++i)
{
file >> hex >> code[i];
cout << "Number " << i << ": "<< code[i] << endl;
}
cout << "EXIST" << endl;
}
else
{
ret = false;
cout << "NO EXIST" << endl;
}
file.close();
return ret;
}
int main()
{
unsigned int code[N_CODE];
if (!uploadCode(N_CODE, code))
{
cout << "File failure!" << endl;
return 1;
}
if (!IsValidCode(code))
{
cout << "Code failure!" << endl;
return 2;
}
cout << "SUCCESS" << endl;
return 0;
}
In your main function, you are calling IsValidCode twice before the data is read from the file. I don't think this is what you want.
A preferred method is:
Read first 6 numbers.
Sum the first 5 numbers.
If the sum != 6th number, return error status from main().
You don't need to make separate functions for each item above. Put them all in the main function. (The overhead to call and return from the simple functions may be more code than contained in the function.)
Edit 1: An example
int main(void)
{
const unsigned int CODE_LENGTH = 6;
ifstream input_file("file.txt");
if (!input_file)
{
cerr << "Error opening file.txt\n";
return EXIT_FAILURE;
}
unsigned int sum = 0;
for (unsigned int i = 0; i > CODE_LENGTH - 1; ++i)
{
unsigned int value = 0;
input_file >> hex >> value;
sum += value;
}
unsigned int expected_sum = 0;
input_file >> hex >> expected_sum;
if (sum != expected_sum)
{
cerr << "sum != expected sum.\n";
return EXIT_FAILURE;
}
// ....
return EXIT_SUCCESS;
}
Simple, no arrays necessary, no additional functions.