How can i make this c++ code work? - c++

This c++ code giving me errors and I dont know how to remove those errors.
code:
#include <iostream>
#include <string>
#include <fstream>
#include <cctype>
#include <iomanip>
using namespace std;
string& RaiseItToUpperCase(string& w)
{
int len = w.length();
for (int index =0; index <len; index++)
w[index]= toupper(w[index]);
return w;
}
void LoadData()
{
string filename;
while(true)
{
cout<<"Enter Data file:";
cin>>filename;
cout<<"Filename entered"<<filename<<endl;
ifstream myfile(filename.c_str());
if(!myfile.good())
{
cout<<"Please Enter a Valid text File"<<endl;
continue;
}
static std::string const targetExtension ("txt");
if (!(filename.size() >= targetExtension.size()
&& std::equal (filename.end() - targetExtension.size(),
filename.end(),
targetExtension.begin() ) ))
{
cout<<"File is not txt"<<endl;
continue;
}
break;
}
string i = filename;
string o;
cout<<"Enter an output file name:"<< endl;
cin>>o;
ofstream output;
ifstream input(filename);
output.open(o.c_str());
int charc =0;
int numw =0;
int longl =0;
int shortl =10000;
while (input>>1)
{
numw++;
charc = charc + i.length() +1;
if (i.length() > longl)
{
longl = i.length();
}
if (i.length() < shortl)
{
i =RaiseItToUpperCase(i);
output << i;
if(input.get() ==32)
{
output<<" ";
}
else
{
output<<"\n";
}
}
charc = charc - 1;
output<<"\nWord Counter Summary\n"<<endl;
output<<"Total Number of Words:"<<numw<<endl;
output<<"Total Number of Characters:"<<charc<<endl;
output<<" Largest Word Size:"<<longl<<endl;
output<<" Smallest Word Size"<<shortl<<endl;
}
}
int main ()
{
LoadData();
return 0;
}
This is c++ file stream program and I am trying to run this code but it giving me errors and i am not able to figure out how remove this errors
so Can anyone tell me how to remove those errors and make this code run
Update
here is the Error:
Error 1 error C2679: binary '>>' : no operator found which takes a
right-hand operand of type 'int' (or there is no acceptable
conversion) c:\users\acer\documents\visual studio
2012\projects\consoleapplication15\consoleapplication15\sour‌​ce.cpp 52 1 ConsoleA‌​pplication15
And thanks in advance

What do you want to do in while (input>>1) ?
If you want read out something:
If you want to read to an integer like int8_t (or int16_t / int32_t etc.):
int8_t number = 0;
while (input >> number)
If you want to read to a char:
char ch;
while (input >> ch)

Related

C++ check is any character in a floating point array from txt file

I am working on a program to read floating point number from an txt file and store in array, and I need to check are there any invalid input like character.
My code is:
int main() {
string line;
ifstream myfile("data.txt");
int size;
float* result;
if (myfile.is_open()) {
getline(myfile, line);
size = stoi(line);
result = new float[size];
for (int i = 0; i < size; i++) {
myfile >> result[i];
/*if ( (isdigit(arr[i])==0) ){
cout << "Invaild input." << endl;
return 0;
}*/
}
myfile.close();
}
else {
return 0;
}
}
The first line of the txt file is the size of the array and the second line is the contents like
5 //size
1 -2 9.2 4.7 -5.2 //content
How can I check that is there any character exist in the array like 1 -2 B 4.7 -5.2 //Invalid input ?
I try the isdigit function but it fail.
If you get an invalid input, reading will fail, and you can check this in the usual manner.
if (myfile >> result[i])
{
// Handle success.
}
else
{
// Handle failure.
}
I have given 2 solutions. One uses built in arrays and other uses std::vector.
Solution 1: Using built in array
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::string line;
std::ifstream inFile("input.txt");
//in case of using array, size must be fixed and predetermined
double arr[120] = {0.0}; //you can choose size according to your needs
if(inFile)
{
double i = 0;//this variable will be used to add element into the array
int count = 0;
while(getline(inFile, line, '\n'))
{
std::istringstream s(line);
//take input(from s to i) and then checks stream's eof flag status
while(s >> i || !s.eof()) {
//check if either failbit or badbit is set
if(s.fail())
{
//clear the error state to allow further operations on s
s.clear();
std::string temp;
s >> temp;
continue;
}
else
{
arr[count] = i;
++count;
//break out of the loop so we do go out of bounds
if(count >=120)//note 120 is the size of the array and you can change it according to your needs
{
break;
}
}
}
}
}
else
{
std::cout<<"file could not be read"<<std::endl;
}
inFile.close();
for(double i: arr)
{
std::cout<<"elem: "<<i<<std::endl;
}
return 0;
}
The output of solution 1 can be seen here.
Solution 2: Using std::vector
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
std::string line;;
std::ifstream inFile("input.txt");
std::vector<double> vec;
if(inFile)
{
double i = 0;//this variable will be used to add element into the vector
while(getline(inFile, line, '\n'))
{
std::istringstream s(line);
//take input(from s to i) and then checks stream's eof flag status
while(s >> i || !s.eof()) {
if(s.fail())
{
//clear the error state to allow further operations on s
s.clear();
std::string temp;
s >> temp;
continue;
}
else
{
vec.push_back(i);
}
}
}
}
else
{
std::cout<<"file could not be read"<<std::endl;
}
inFile.close();
for(double i: vec)
{
std::cout<<"elem: "<<i<<std::endl;
}
return 0;
}
The ouput of solution 2 can be seen here.
Important Note
The advantage of using std::vector over built in array(in this case) is that you don't have know the size of the vector beforehand. So it is preferable because you don't know how many integers are there in the input.txt file. std::vector can handle this correctly(dynamically). But when using built in arrays you must know/specify the size of the array beforehand. This in turn means you must know beforehand how many integers are there in the input.txt, which is not practical.

How to start reading file from a particular position c++

I am reading a file using fstream and getline functions. I want to give a starting position e.g. my file has 13 lines I want to start reading it from 7th line for example. Here is my code:
#include<iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include<iterator> // for iterators
#include<map>
using namespace std;
int main()
{
string line;
int start= 7;
unsigned long int index;
For( int z=1; z<=13; z++){
if (f_node.is_open())
{
getline(f_node, line);
if ((line.find("$EndNodes") != string::npos))
{
cout << "$EndNodes found file closed .... " << endl;
f_node.close();
return false;
}
// Point index.
int i = 0;
int j = line.find_first_of(" ", i);
index = strtoul((line.substr(i, j)).c_str(), NULL, 0);//
}
}
I am reading only indexes and I want to start it from 7th index How to do it?
To discard some number of lines, something like:
#include <fstream>
#include <string>
int main() {
std::ifstream infile{"myfile.txt"};
std::string line;
int starting_line = 7;
// Read and discard beginning lines
for (int n = 1; n < starting_line; n += 1) {
if (!std::getline(infile, line)) {
// Error or premature end of file! Handle appropriately.
}
}
while (std::getline(infile, line)) {
// Do something with the lines you care about.
}
return 0;
}
Except with actual error checking and handling and such.
"there is no way to tell code the starting position like seekg and tellg?" No. NL is just like any other character, it does not receive any special treatment.
You simply must scan the stream, counting the new-line character:
std::istream& seek_line(std::istream& is, const int n, std::ios_base::seekdir way = std::ios_base::beg)
{
is.seekg(0, way);
int i = 0;
char c;
while (is.get(c) && i < n)
if (c == '\n')
++i;
is.putback(c);
return is;
}
And this is how you use the above function:
int main()
{
using namespace std;
ifstream is{ "c:\\temp\\test.txt" };
if (!is)
return -1;
if (!seek_line(is, 3))
return -2;
string s;
getline(is, s);
cout << s << endl;
return 0;
}

accessing data within array of structure in C++

This is an assignment that required me to use ifstream to stream a CSV file. this csv file contains 52 state names and amount of different resources used by each state. for example:
Alabama,410.20,715.70,169.40,18.00,44.90,309.10,11.90,417.30,64.50,167.40,23.70,0.10,0.40,0.00
then I need to prompt the user to type the state name and the output is the percentage of resources used.
I created a struct containing a string type and an array to store the value of each state and created an array of struct to store multiple state's data, but I am not sure whether my code is right, and I want to know how to access other data, such as the data store in my double array, when the user input a state name.
here is my code:
struct statData
{
string statename;
double StatDataNumber[14];
}DataStruc[51];
int main()
{
ifstream indata;
string line;
statData State;
State.statename;
statData Consumption;
Consumption.StatDataNumber;
indata.open("Data2016.csv"); //opening file
if (indata.fail()) //fail safe
{
cout << "Fail to open file";
exit(1);
}
getline(indata, line); //skipping the first line of the csv file
int i;
int N = 0;
int NLoop;
int Loop = 0;
string InvertValueBefore;
double InvertValueAfter;
char comma;
while (indata.eof()) // before file reache the end
{
for (NLoop = 0; NLoop < 51; NLoop++) // struct array loop
{
{
getline(indata, DataStruc[Loop].statename, ',');// getting statename
for (i = 0; i <= 12; i++) // each group of data, except last
{
indata >> DataStruc[Loop].StatDataNumber[N] >> comma;// storing data in struct
N++;
}
getline(indata, InvertValueBefore); // store last value as string
InvertValueAfter = stoi(InvertValueBefore); // convert it into double
InvertValueAfter = DataStruc[Loop].StatDataNumber[N]; // store it in array of struct
}
Loop++;
}
}
ReadData();
return 0;
}
void ReadData (ifstream& indata , statData DataStruc[] )
{
int i;
string input;
bool stayinloop = true;
cout << "Enter a statename or 'q' to quit\n";
getline(cin, input);
while (stayinloop == true)
{
if (input == "Alabama")
DataStruc[i].statename == "Alabama";
DataStruc[i].StatDataNumber[]
}
}
this code is not finished. Please let me know if you spot any other error. Thank you!
Your code is fine. However, certain points:
1. You just need to get rid of certain variables which are not required.
2. The "eof" function is used to identify if the end of file is reached. For which, you need to use while (!indata.eof()).
3. The "ReadData" method should appear before the main function, however, if you want to have your functions after the main function then first you need to define your function declaration before the main function (i.e. before main function, you can put "void ReadData (ifstream& indata , statData DataStruc[]);"), afterwards you can define your function.
Below is a working version of your requirements.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
struct statData
{
string statename;
double StatDataNumber[3];
}DataStruc[2];
void ReadData (ifstream& indata , statData DataStruc[])
{
string input;
bool stayinloop = true;
while (stayinloop)
{
cout << "\nEnter a statename or 'q' to quit\n";
getline(cin, input);
for (int i = 0 ; i < 2; i++)
{
if (input == DataStruc[i].statename)
{
for(int j = 0 ; j < 3; j++)
{
cout << DataStruc[i].StatDataNumber[j] << ',';
}
}
else if(input == "q")
{
stayinloop = false;
}
}
}
}
int main()
{
ifstream indata;
string tempData = "";
string line;
string InvertValueBefore = "";
double InvertValueAfter = 0.0;
char comma = ',';
indata.open("test.csv"); //opening file
if (indata.fail()) //fail safe
{
cout << "Fail to open file";
}
getline(indata, line); //skipping the first line of the csv file
while (!indata.eof()) // before file reach the end
{
for (int NLoop = 0; NLoop < 2; NLoop++) // struct array loop
{
{
getline(indata, DataStruc[NLoop].statename, comma);// getting statename
for (int i = 0; i < 2; i++) // each group of data, except last
{
getline(indata, tempData, comma);
DataStruc[NLoop].StatDataNumber[i] = atof(tempData.c_str());
}
getline(indata, InvertValueBefore); // store last value as string
InvertValueAfter = atof(InvertValueBefore.c_str()); // convert it into double
DataStruc[NLoop].StatDataNumber[2] = InvertValueAfter;
}
}
}
ReadData(indata, DataStruc);
return 0;
}

extracting digits from input string c++

I'm trying to do parsing to some input string reactions read from file at formula :2W+B=8A+10Z, I'm not interested in characters i need only to split and extract the integer values to put them in a vector i.e vector associated with the reaction here is :[2 1 8 10]
i thought about many things: std::strtok(),isdigital(),find_first_of() but they all didn't work for integer values ... can any body help ??
here my try:
int main()
{
std::string input;
std::getline(std::cin, input);
std::stringstream stream(input);
while(1) {
int n;
stream >> n;
char * pch;
pch = strtok (input," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.");
}
}
}
This will do what you want in this particular case. However, i suggest that you look into regex to parse your equation better. You may want to consider all possible cases for your input. This includes \,-,* and other operators that you may want to add in your equation. Also, I'm assuming variables in your equation has only one character.
int main()
{
string input;
getline(std::cin, input);
stringstream stream(input);
char tmp[256];
const char *in = input.c_str();
char str[256];
strcpy(str,in);
int x;
tmp[0]='\0';
char c;
vector<int> vec;
//Scan for the digit
//if it is, store the rest of the string back to str
//if it isn't, store the part of the string before a digit to tmp
while (sscanf(str,"%d%s",&x,str) || sscanf(str,"%[^0123456789]%s",tmp,str) > 1)
{
//check if tmp has the form [variable name]+[a string]
//a string can include another variable name and an operator, = in this case
while(sscanf(tmp,"%c+%[^0123456789]",&c,tmp) > 1)
vec.push_back(1);
if (tmp[0]=='\0')
vec.push_back(x);
tmp[0]='\0';
}
//just in case there're more special cases
while(sscanf(str,"%c+%[^0123456789]",&c,str) > 1)
vec.push_back(1);
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << endl;
}
Output:
2
1
8
10
See comments for explanation.
EDIT
Be careful when you have a special case 2W+B=8A+10Z+C+D. Notice the last C D should both have coefficients 1. This could happen in the middle of the equation too.
Here is another solution:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string equ;
vector<int> digits;
cout << "enter your equation: \n";
cin >> equ;
for (auto i : equ)
{
if (isdigit(i))
{
digits.push_back(stoi(string{i}));
}
}
for (auto& i : digits)
{
cout << i << endl;
}
system("pause");
return 0;
}
You could simply do something like this, for comments see code
#include <iostream>
#include <string>
#include <vector>
std::vector<int> Split(std::string str)
{
std::vector<int> result; // will contain the different ints
// set pointer to first character in the string
char const* pch = str.c_str();
std::string digit; // buffer to keep digits if more than one
int sign = 1; // each number has a sign -1 or 1
for (; *pch; ++pch)
{
if (std::isdigit(*pch)) // if a digit, put in temp buffer
{
digit += *pch;
}
else if (std::isalpha(*pch)) // if not a digit evaluate the ones we have
{
if (digit.empty()) // none so assume 1 before letter e.g. W+2B
{
result.push_back(1*sign);
}
else
{
result.push_back(stoi(digit)*sign);
digit = "";
}
}
else // determine sign of number
{
digit = "";
if (*pch == '+')
{
sign = 1;
}
else if (*pch == '-')
{
sign = -1;
}
}
}
return result;
}
int main()
{
using namespace std;
string expr{"-2W+B=-8A+10Z"};
auto digits = Split(expr);
for (auto& digit : digits)
{
cout << digit << endl;
}
return 0;
}

C++ Hex string to byte array

First off, I've Googled this question over the past few days but everything I find doesn't work. I don't receive runtime errors but when I type in the same key (in the form of a hex string) that the program generates to encrypt, decryption fails (but using the generated key throughout the program works fine). I'm trying to enter a hex string (format: 00:00:00...) and turn it into a 32-byte byte array. The input comes from getpass(). I've done this before in Java and C# but I'm new to C++ and everything seems much more complicated. Any help would be greatly appreciated :) Also I'm programming this on a linux platform so I'd like to avoid Windows-only functions.
Here is an example of what I've tried:
char *pass = getpass("Key: ");
std::stringstream converter;
std::istringstream ss( pass );
std::vector<byte> bytes;
std::string word;
while( ss >> word )
{
byte temp;
converter << std::hex << word;
converter >> temp;
bytes.push_back( temp );
}
byte* keyBytes = &bytes[0];
If your input has format: AA:BB:CC,
you could write something like this:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdint>
struct hex_to_byte
{
static uint8_t low(const char& value)
{
if(value <= '9' && '0' <= value)
{
return static_cast<uint8_t>(value - '0');
}
else // ('A' <= value && value <= 'F')
{
return static_cast<uint8_t>(10 + (value - 'A'));
}
}
static uint8_t high(const char& value)
{
return (low(value) << 4);
}
};
template <typename InputIterator>
std::string from_hex(InputIterator first, InputIterator last)
{
std::ostringstream oss;
while(first != last)
{
char highValue = *first++;
if(highValue == ':')
continue;
char lowValue = *first++;
char ch = (hex_to_byte::high(highValue) | hex_to_byte::low(lowValue));
oss << ch;
}
return oss.str();
}
int main()
{
std::string pass = "AB:DC:EF";
std::string bin_str = from_hex(std::begin(pass), std::end(pass));
std::vector<std::uint8_t> v(std::begin(bin_str), std::end(bin_str)); // bytes: [171, 220, 239]
return 0;
}
How about this?
Read it as a word and operate on it after?
You can do any size checking format checking in convert().
#include <iostream>
#include <string>
#include <vector>
char convert(char c)
{
using namespace std;
// do whatever decryption stuff you want here
return c;
}
void test()
{
using namespace std;
string word;
cin >> word;
vector<char> password;
for (int i = 0; i < word.length(); i++)
{
password.push_back(convert(word[i]));
}
for (int i = 0; i < password.size(); i++)
{
cout << password[i];
}
cout << "";
}
int main()
{
using namespace std;
char wait = ' ';
test();
cin >> wait;
}
Are there specific reasons for not using cin here?