I am trying to get some values line by line from a text file:
17.09 284.60 486.01 34.12 12.04 1.20 2.33 36.85 73.44
31.25 196.09 323.26 69.76 47.33 79.82 11.42 27.97 66.61
28.76 41.45 992.29 1.29 42.33 10.83 19.16 5.86 1.88
Taking these values and putting it into a vector. Each row has values to be used in a calculation.
My code:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
using namespace std;
int main() {
ifstream xfile;
string input;
double num=0;
int count = 0;
vector <double> myvector;
cout << "Input the file: ";
cin >> input;
xfile.open(input);
if (xfile.is_open()) {
cout << "File accessed!" << endl;
while (getline(xfile, input)) {
count++;
myvector.push_back(num);
}
}
else {
cout << "File opening failed!"<<endl;
}
cout << "Numbers of lines in the file : " << count << endl;
for (int i = 0; i < myvector.size(); i++) {
cout << myvector[i] << "\t";
}
cin.fail();
return 0;
}
My output is somewhat correct, only that it is printing out just zeroes:
https://ibb.co/xqwT1hR
EDIT: the input is for the name of file. "ahu_long.txt"
You never used your num variable.
double num=0;
....
....
size_t pos = 0;
std::string token;
while (getline(xfile, input)) {
count++;
// you need convert your "input" to a double and save it to "num"
while ((pos = input.find(" ")) != std::string::npos) {
token = input.substr(0, pos);
// std::cout << token << std::endl;
num = atof(token.c_str());
myvector.push_back(num);
input.erase(0, pos + delimiter.length());
}
}
Change your variable with what you read from the file.
Related
So I have built a small basic data encrypter (for learning purposes only). It is working perfectly fine but it reads only a single line of input. Is it my Editor problem or my code have some issues.
ps: I use CodeBlocks
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
std::string str;
char enc;
int word;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
cout << "Enter a Word: ";
getline(cin, str);
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(int i = 0; i < str.length(); i++){
int randomAdd[5] = {5,6,2,3,2};
int size = sizeof(randomAdd)/sizeof(randomAdd[0]);
// for(int j = 0; j < 5; j++){
word = str.at(i);
if(i%5 == 0){
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
return 0;
}
This works
Hello World
But I cannot enter this
Hello World
Have a nice day
because then the program exits command prompt without any error or message.
How can I read more than one line?
You can do as
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
cout << str << endl;
}
return 0;
}
This code sample allows you to input multiple lines interactively from the command line/shell
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
char enc;
int word;
vector<string> myInput;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
while (str != "Enigma")
{
cout << "Enter a line (Write Enigma to exit input): ";
getline(cin, str);
myInput.push_back(str);
}
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(auto & myInputLine : myInput)
{
str = myInputLine;
for (size_t i = 0; i < str.length(); i++) {
int randomAdd[5] = { 5,6,2,3,2 };
int size = sizeof(randomAdd) / sizeof(randomAdd[0]);
word = str.at(i);
if (i % 5 == 0) {
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
}
return 0;
}
The input is finished if Enigma is written.
All input is stored in the vector container of the STL, see vector.
Afterwards, all the lines are encrypted by your algorithm.
Hope it helps?
I want to retrieve the first value of speed in from the typedef struct variable which I have added into the map. Right now my code is returning all the values from the CSV file which I have read. How do I get it to return only the first value to do a comparison to get the max value from the entire column?
I have tried using map.begin()->((*it).second).speed) but it does not work.
#include <iostream>
#include <fstream>
#include <string>
#include "Date.h"
#include "Time.h"
#include <stdlib.h>
#include <map>
using namespace std;
typedef struct
{
Time t;
float speed;
int solar;
}
WindLogType;
date d;
multimap<date, WindLogType> windlog;
ifstream input , csv;
ofstream output;
string filename;
int number,choice;
string *filelist = NULL;
WindLogType T1;
int main()
{
output.open("data/met_index.txt");
cout << "Enter number of file to read : " << endl;
cin >> number ;
for(int i =0; i< number ; i++)
{
cout << "Enter File name : " << endl;
cin >> filename;
output << filename << endl;
}
filelist = new string[number];
output.close();
input.open("data/met_index.txt", ios::in);
if(!input.is_open())
{
cout<< "File not found."<<endl;
return 0;
}
else
{
string line, line2;
while(getline(input, line, '\n'))
{
//cout << line << endl;
line = "data/" + line;
for(int i =0; i<number; i++)
{
filelist[i] = line;
cout << filelist[i];
csv.open(filelist[i].c_str());
string line,sDay, sMonth, sYear, sHH, sMM;
while(getline(csv,line2, '\n' ))
{
//cout << line2 << endl;
getline(csv, sDay,'/');
getline(csv, sMonth,'/');
getline(csv, sYear,' ');
getline(csv, sHH,':');
getline(csv, sMM,',');
int day1 = atoi(sDay.c_str());
int month1 = atoi(sMonth.c_str());
int year1 = atoi(sYear.c_str());
int hour1 = atoi(sHH.c_str());
int min1 = atoi(sMM.c_str());
float s1 = 0.0;
int sr = 0;
for (int i=0; i<10; i++)
{
csv >> s1;
csv.ignore(100, ',');
}
for(int j =0; j<18; j++)
{
csv >> sr;
csv.ignore(50,',');
}
T1.t.setTime(hour1, min1);
T1.speed = s1;
T1.solar = sr;
d.setDate(day1, month1, year1);
windlog.insert(pair<date, WindLogType>(d, T1));
multimap<date, WindLogType> :: iterator it;
for(it =windlog.begin(); it!= windlog.end(); ++it)
{
int max_value = ((*it).second).speed;
if((*it).second.speed > max_value){
max_value = ((*it).second).speed;
}
cout << max_value<<endl;
}
}
csv.close();
}
/**/
}
input.close();
input.clear();
//input.open(filelist[0].c_str(), ios::in);
}
return 0;
}
Your are printing max_value everytime.
Move the lines that find the maximum value after you've inserted everything, i.e., after the csv.close() for example. Also, do not print the maximum while searching for it but after you've iterated over all the elements.
multimap<date, WindLogType> :: iterator it =windlog.begin();
int max_value = ((*it).second).speed;
for(++it ; it!= windlog.end(); ++it)
{
if((*it).second.speed > max_value){
max_value = ((*it).second).speed;
}
}
cout << max_value<<endl;
Of course, be sure the map is not empty.
EDIT
WindLogType.speed is a float and you're using an integer when finding the maximum, it should be float too. Probably you already know it, but since C++11 you can use the auto specifier to let the compiler deduce automatically the correct type based on the assignment expression. It is available since Visual Studio 2010 and gcc 4.4 (for gcc you have to include the --std=c++11 option).
if (!windlog.empty()) {
auto it = windlog.begin(); // 'it' is an iterator
auto max_value = it->second.speed; // you're now sure it uses the same type
for(++it; it!= windlog.end(); ++it) {
max_value = std::max(it->second.speed, max_value);
}
std::cout << max_value << std::endl;
} else {
std::cout << "Empty map" << std::endl;
}
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int search(string pat, string txt)
{
int M=(int)pat.length();
int N=(int)txt.length();
int occurences=0;
for (int s=0; s<=N-M; s++)
{
int j;
for (j=0; j<M; j++)
{
if (txt[s+j]!= pat[j])
break;
}
if (j==M)
{
occurences++;
}
}return occurences;
}
int main()
{
string pat;
string txt;
int line = 1;
cout << "Pattern: ";
cin >> pat;
cout << endl;
ifstream infile("/Users/irem/Library/Developer/Xcode/DerivedData/sample2.txt");
while (getline(infile, txt))
{
cout << "Line " << line << ": " << search(pat, txt) << " occurences" << endl;
line++;
}
return 0;
}
my code perfectly read the file and search for a given string in the text file.But i want the information that which line how many occurrences while search function making string matching?Line information always stay at 1.
Like the title says I'm trying to read an unknown number of integers from a file and place them in a 2d array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream f;int i,j,n,a[20][20];char ch;
i=0;j=0;n=0;
f.open("array.txt", ios::in);
while(!f.eof())
{
i++;
n++;
do
{
f>>a[i][j];
j++;
f>>ch;
}
while(ch!='\n');
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cout<<a[i][j]<<endl;
cout<<endl;
}
return 0;
}
and my "array.txt" file :
1 1 1
2 2 2
3 3 3
After compiling the program, it prints this
As your input file is line oriented, you should use getline (C++ equivalent or C fgets) to read a line, then an istringstream to parse the line into integers. And as you do not know a priori the size, you should use vectors, and consistently control that all lines have same size, and that the number of lines is the same as the number of columns.
Last but not least, you should test eof immediately after a read and not on beginning of loop.
Code becomes:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
fstream f;
int i=0, j=0, n=0;
string line;
vector<vector<int>> a;
f.open("array.txt", ios::in);
for(;;)
{
std::getline(f, line);
if (! f) break; // test eof after read
a.push_back(vector<int>());
std::istringstream fline(line);
j = 0;
for(;;) {
int val;
fline >> val;
if (!fline) break;
a[i].push_back(val);
j++;
}
i++;
if (n == 0) n = j;
else if (n != j) {
cerr << "Error line " << i << " - " << j << " values instead of " << n << endl;
}
}
if (i != n) {
cerr << "Error " << i << " lines instead of " << n << endl;
}
for(vector<vector<int>>::const_iterator it = a.begin(); it != a.end(); it++) {
for (vector<int>::const_iterator jt = it->begin(); jt != it->end(); jt++) {
cout << " " << *jt;
}
cout << endl;
}
return 0;
}
You may want to look into using a vector so you can have a dynamic array.
Try:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
fstream f;
int i, j, n, a[20][20];
string buf;
i = 0;
j = 0;
n = 0;
f.open("array.txt", ios::in);
while (1) {
getline(f, buf);
if (f.eof()) break;
stringstream buf_stream(buf);
j = 0;
do {
buf_stream >> a[i][j];
j++;
} while (!buf_stream.eof());
i++;
n++;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Also, if you really want to read arbitrarily large arrays, then you should use std::vector or some such other container, not raw arrays.
I hope someone can help me with this issues. I am creating a HTML lexical analyzer in c++. According to the teacher I am supposed to have 3 files. one header and 2 main .cpp and it should be able to read a file
This is my file try.txt
<<<<<Hello there <H1 style=”BOLD”>header!!</H1>
<<
<< =
This is my header
#ifndef tokens_h
#define tokens_h
#include <string>
#include <iostream>
enum tokens {TEXT, LANGLE = 60, RANGLE = 62, SLASH = 47, ID, EQ = 61, QSTRING = 34, OTHER, END};
/* TEXT = 0
LANGLE = 60
RANGLE = 62
SLASH = 47
ID = 48
EQ = 61
QSTRING = 34
OTHER = 36
END = 36
*/
int getToken(std::istream *br, std::string a);
#endif
This is my main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include "tokens.h"
using namespace std;
int main(int argc, char *argv[])
{
//defineTokens();
istream *br;
ifstream infile;
string output;
int a;
vector<int> count;
int langle = 0;
string line;
if(argc == 1){
while(cin.good() ){ //Get continous input
br = &cin;
getline(cin,line);
getToken(br,line);
}
}
else if(argc != 2){
return 1;
}else{
infile.open(argv[1]);
if( infile.is_open()){
br = &infile;
while(!infile.eof()){
getline(infile,output);
getToken(br,output);
}
}
else{
cout << argv[1] << "Can't Be Opened" << endl;
return 1;
}
}
}
and this is my tokens.cpp where I print the results
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <utility>
#include "tokens.h"
using namespace std;
void compar(int ch)
{
vector<int> text;
vector<int> langle;
//string langle;
vector<int> rangle;
vector<int> slash;
vector<int> id;
vector<int> eq;
vector<int> qstring;
vector<int> other;
map <string, int> result;
int c=0;
int d=0;
int sum;
string r;
switch(ch){
case 60:static int countlangle = 0;
countlangle ++;
result["LANGLE"]= countlangle;
cout << "LANGLE: " << result["LANGLE"] << " ";
break;
case 62:static int countrangle = 0;
countrangle ++;
result["RANGLE"]= countrangle;
cout << "RANGLE: " << result["RANGLE"] << " ";
break;
case 47:static int countslash = 0;
countslash ++;
result["SLASH"]= countslash;
cout << "SLASH: " << result["SLASH"] << " ";
break;
case 61:static int counteq = 0;
counteq ++;
result["EQ"]= counteq;
cout << "EQ: " << result["EQ"] << " ";
break;
case 34:static int countqstring = 0;
countqstring ++;
result["QSTRING"]= countqstring;
cout << "QSTRING: " << result["QSTRING"] << " ";
break;
}
}
int getToken(istream *br, string a)
{
int b;
string d = "no";
string f = "no";
string r;
vector<char> st;
vector<string> trial;
vector<int> countr;
vector<int> countl;
vector<char> quotes;
string ans;
int x=0;
r = a;
cout << a[27];
int found;
found = a.find('\"');
cout << found<<"XXxxxxxX";
for(int i = 0; i< a.length();i++){ //read entire string
if(a[i] == '<'){
// cout << LANGLE << " ";
d="yes";
x +=1;
countr.push_back(LANGLE);
//cout << count.size();
//cout << x;
compar(LANGLE);
b =LANGLE;
// return LANGLE;
}
else if(a[i]== '>' && d == "yes"){
f = "yes";
b = RANGLE; //assing to the int variable the value from the enum header
compar(RANGLE);
}
else if(a[i]== '/' && d == "yes"){
compar(SLASH);
}
else if(a[i] == '=' && d == "yes"){
compar(EQ);
}
else if(a[found] == '\"' && d == "yes"){
// for(int k =0;k < quotes.size();k++)
//cout << r[found] <<"XXX";
compar(QSTRING);
}
}
return 0;
}
The program reads <>= without a problem but when I try to read a '\"' with cout << a[27];
I get this: ?
if I print cout << a;
i get <<<<<Hello there <H1 style=”BOLD”>header!!</H1> // this is the string I am trying to read
when I use found = a.find('\"'); it gives me a -1
My question is why my program cannot recognized quotes? is it the way I am reading the file?
thanks in advance
Your file contains:
”
whereas your lexer looks for:
"
These are distinct.