"unkown parser error" in c++ netbeans - c++

Sorry in advance, I posted a picture but I don't have the rep yet :( The error at line 1 says "Unknown parser error" repeated over four lines, and starting at the ReadFile class line pretty much each line has an error saying "unexpected token". I have included all of the custom header files from a folder either by right clicking "header" under project and adding the folder containing them or by right clicking the project name itself and adding the folder there. The private folder containing the private snippets of the headers are also included. Anyone have any ideas? This is for a free collection of lectures by Stanford, and you have to download and install their custom headers.. The instructor is using Visual c++, but that shouldn't mean I can't use the files for Netbeans right, their just .h files..?
#include "genlib.h"
#include <iostream>
#include <fstream>
#include "map.h"
#include "random.h"
#include "set.h"
using namespace std;
void ReadFile(ifstream &in, Map<int> &m)
{
while (true) {
string word;
in >> word;
if (in.fail()) break;
if (m.containsKey(word))
m[word]++;
else
m[word] = 1;
}
Map<int>::Iterator itr = m.iterator();
string max;
int maxCount = 0;
while (itr.hasNext()) {
string key = itr.next();
if (m[key] > maxCount) {
max = key;
maxCount = m[key];
}
}
cout << "Max is " << max << " = " << maxCount << endl;
}
void TestRandom()
{
Set<int> seen;
while (true) {
int num = RandomInteger(1, 100);
if (seen.contains(num)) break;
seen.add(num);
}
Set<int>::Iterator itr = seen.iterator();
while (itr.hasNext())
cout << itr.next() << endl;
}
int main()
{
ifstream in("burgh.txt");
Map<int> counts;
ReadFile(in, counts);
Randomize();
TestRandom();
return 0;
}

In your ReadFile function (in multiple places) you are attempting to use a string as the key to a Map with integers as keys.
string word;
in >> word;
if (in.fail()) break;
if (m.containsKey(word))
m[word]++;
In order to do this properly you will need to parse your string input into an integer. This can be achieved through the stoi function or similar.
Example
string word;
in >> word;
int iKey = stoi(word, nullptr);
if (in.fail()) break;
if (m.containsKey(iKey))
m[iKey]++;

Related

replacing string based on user input c++

i want to receive an input from user and search a file for that input. when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input. (I'm writing a hospital management app and this is a part of project that patients and edit their document).
i completed 90 percent of the project but i don't know how to replace it. check out following code:
#include <iostream>
#include <stream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in|ios::out);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
Myfile.close();
}
for example my file contains this line ( David , ha , 2002 ) and user wants to change 2002 to 2003
You cannot replace the string directly in the file. You have to:
Write to a temporary file what you read & changed.
Rename the original one (or delete it if you are sure everything went fine).
Rename the temporary file to the original one.
Ideally, the rename part should be done in one step. For instance, you do not want to end up with no file because the original file was deleted but the temporary one was not renamed due to some error - see your OS documentation for this.
Here's an idea:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
void replace(string& s, const string& old_str, const string& new_str)
{
for (size_t off = 0, found_idx = s.find(old_str, off); found_idx != string::npos; off += new_str.length(), found_idx = s.find(old_str, off))
s.replace(found_idx, old_str.length(), new_str);
}
int main()
{
const char* in_fn = "c:/temp/in.txt";
const char* bak_fn = "c:/temp/in.bak";
const char* tmp_fn = "c:/temp/tmp.txt";
const char* out_fn = "c:/temp/out.txt";
string old_str{ "2002" };
string new_str{ "2003" };
// read, rename, write
{
ifstream in{ in_fn };
if (!in)
return -1; // could not open
ofstream tmp{ tmp_fn };
if (!tmp)
return -2; // could not open
string line;
while (getline(in, line))
{
replace(line, old_str, new_str);
tmp << line << endl;
}
} // in & tmp are closed here
// this should be done in one step
{
remove(bak_fn);
rename(in_fn, bak_fn);
remove(out_fn);
rename(tmp_fn, in_fn);
remove(tmp_fn);
}
return 0;
}
One possible way:
Close the file after you read it into "line" variable, then:
std::replace(0, line.length(), "2002", "2003")
Then overwrite the old file.
Note that std::replace is different from string::replace!!
The header is supposed to be <fstream> rather than <stream>
you can't read and write to a file simultaneously so I have closed the file after reading before reopening the file for writing.
instead of updating text inside the file, your line can be updated and then written to file.
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line, line2;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
int index = line.find(word);
if (index != string::npos){
Myfile.close();
Myfile.open("Patientlist.txt", ios::out);
line.replace(index, word.length(), replacement);
Myfile.write(line.data(), line.size());
Myfile.close();
}
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
}

Checking a file against itself

I am trying to write a program that checks how many words are inside of other words. Then tell the user which word has the most words in it. For some reason, the while loop is breaking and I cannot get the file to reload. Any ideas?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct finalWord {
string word;
int number;
};
ostream& operator<<(ostream& o, const finalWord& f) {
return o << f.word << ": " << f.number;
}
int main () {
finalWord f;
string line, holder, line2;
ifstream myFile("enable1.txt");
int counter;
int holdlen;
size_t found;
if (myFile.is_open()){
while(getline(myFile,line)){
holder = line;
while (getline(myFile, line)){
found = holder.find(line);
if (found != string::npos){
counter++;
}
if (counter > holdlen) {
f.word = line;
f.number = counter;
holdlen = counter;
}
counter = 0;
}
}
}
cout << f << endl;
}
Actually the problem you are facing is because of the two loops you are using with same myFile
IN First WHILE loop it will take a word
IN Second WHILE loop it will go through the rest of the file.
It will be an issue in the following case.
If a String "I am Happy" is occurred more than once then it will iterate for each occurrence to search up to end of the file.
So to avoid that you need to take the unique strings in an vector as said by Vaughn Cato and then do a check for the occurrence of that string in the whole file to make it efficient.

Using the getword function c++

Am I using the getword function wrong here? The compiler keeps telling me that there is no member function.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
int OccuranceOfString(ofstream & Out)
{
string Occur;
string Temp;
int OccurLength;
int count;
cout << "please enter to string to search for";
cout << endl;
cin >> Occur;
OccurLength = Occur.length();
while(Out.getword(Temp))
{
if (Temp == Occur)
{
count ++;
}
}
return count;
}
Whats wrong with my code? I'm trying to find all occurances of a string with this function
std::ofstream has no getword function: see here.
Perhaps you're thinking of std::getline.
There is no function getword in the header files listed. You simply must construct a function that will extract words from a line. capture a line by
getline(out,line);
line will have your line of string and use line[index] to get continuous characters to be equal to a word.
You can use this
std::string::find
do something like this..
int pos = 0;
int occurrences = 0
string input = "YAaaaAH";
string find = "a";
while(pos != -1){
pos = input.find(find,pos);
occurrences++;
}
text file :
code :
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream file("DB_name_age.txt");
int index;
string name;
int age;
if(file.is_open())
{
while(file >>index >> name >>age)
{
cout << index <<" "<<name <<" "<<age << endl;
}
}else{
cout<< "file open fail" <<endl;
}
return 0;
}
visual explanation:

How to get part of an .csv file in C++?

I am pretty new to C++.
I just want to get a certain field on a ".csv" file, not all off it.
I am pretty sure, it must be very easy, but I don't know how to do it.
Here is my code to get all the ".csv" content :
#include <iostream>
#include <fstream>
#include <string>
// #include "Patient.h"
using namespace std;
int main()
{
// CPatient patient;
ifstream file("C:/Users/Alex/Desktop/STAGE/test.csv");
if(file)
{
// the file did open well
string line;
while(getline(file, line, ';')) //Until we did not reach the end we read
{
cout << line << endl; //Console Result
}
}
else
{
cout << "ERROR: Could not open this file." << endl;
}
system("PAUSE");
return 0;
}
If you can use boost libraries, then boost::tokenizer would provide the functionality you require. Most notablty, it correctly handles quoted field values that contain commas. The following is a code snippet copied from the linked page:
// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int main(){
using namespace std;
using namespace boost;
string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
tokenizer<escaped_list_separator<char> > tok(s);
for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin();
beg!=tok.end();
++beg)
{
cout << *beg << "\n";
}
}
You could pass each ligne read to a tokenizer and extract the fields you require.
Try reading whole lines and split them afterwards:
int N = 5; // search the fifth field
char separator = ';';
while (std::getline(fichier, ligne)) {
// search for the Nth field
std::string::size_type pos = 0;
for (int i = 1; i < N; ++i)
pos = ligne.find_first_of(separator, pos) + 1;
std::string::size_type end = ligne.find_first_of(separator, pos);
// field is between [pos, end)
}

C++ program to read a txt file and sort data

I'm a physics PhD student with some experience coding in java, but I'm trying to learn C++.
The problem I'm trying to solve is to read in data from a .txt file and then output all the numbers > 1000 in one file and all those <1000 in another.
What I need help with is writing the part of the code which actually reads in the data and saves it to an array. The data itself is only separated by a space, not all on a new line, which is confusing me a bit as I don't know how to get c++ to recognise each new word as an int. I have canabalised some code I have got from various sources online-
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include<cmath>
using namespace std;
int hmlines(ifstream &a) {
int i=0;
string line;
while (getline(a,line)) {
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a) {
int i=0;
char c;
a >> noskipws >> c;
while ((c=a.get()) && (c!=EOF)){
if (c==' ') {
i++;
}
}
return i;
}
int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "Input filename- ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()) {
goto start;
}
matos.seekg(0, ios::beg);
w = hmwords(matos);
cout << w;
/*c = hmchars(matos);*/
int RawData[w];
int n;
// Loop through the input file
while ( !matos.eof() )
{
matos>> n;
for(int i = 0; i <= w; i++)
{
RawData[n];
cout<< RawData[n];
}
}
//2nd Copied code ends here
int On = 0;
for(int j =0; j< w; j++) {
if(RawData[j] > 1000) {
On = On +1;
}
}
int OnArray [On];
int OffArray [w-On];
for(int j =0; j< w; j++) {
if(RawData[j]> 1000) {
OnArray[j] = RawData[j];
}
else {
OffArray[j] = RawData[j];
}
}
cout << "The # of lines are :" << l
<< ". The # of words are : " << w
<< "Number of T on elements is" << On;
matos.close();
}
But if it would be easier, i'm open to starting the whole thing again, as I don't understand exactly what all the copied code is doing. So to summarise, what I need is it to-
Ask for a filepath in the console
Open the file, and store each number (separated by a space) as an element in a 1D array
I can manage the actual operations myself I think, if I could just get it to read the file the way I need.
Thanks very much
Using C++11 and the Standard Library makes your task fairly simple. This uses Standard Library containers, algorithms, and one simple lambda function.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string filename;
std::cout << "Input filename- ";
std::cin >> filename;
std::ifstream infile(filename);
if (!infile)
{
std::cerr << "can't open " << filename << '\n';
return 1;
}
std::istream_iterator<int> input(infile), eof; // stream iterators
std::vector<int> onvec, offvec; // standard containers
std::partition_copy(
input, eof, // source (begin, end]
back_inserter(onvec), // first destination
back_inserter(offvec), // second destination
[](int n){ return n > 1000; } // true == dest1, false == dest2
);
// the data is now in the two containers
return 0;
}
Just switch the type of variable fed to your fistream, created from new std:ifstream("path to file") into a int and c++ will do the work for you
#include <fstream> //input/output filestream
#include <iostream>//input/output (for console)
void LoadFile(const char* file)
{
int less[100]; //stores integers less than 1000(max 100)
int more[100]; //stores integers more than 1000(max 100)
int numless = 0;//initialization not automatic in c++
int nummore = 0; //these store number of more/less numbers
std::ifstream File(file); //loads file
while(!file.eof()) //while not reached end of file
{
int number; //first we load the number
File >> number; //load the number
if( number > 1000 )
{
more[nummore] = number;
nummore++;//increase counter
}
else
{
less[numless] = number;
numless++;//increase counter
}
}
std::cout << "number of numbers less:" << numless << std::endl; //inform user about
std::cout << "number of numbers more:" << nummore << std::endl; //how much found...
}
This should give you an idea how should it look like(you shoudnt use static-sized arrays tough) If you got any probs, comment back
Also, please try to make nice readable code, and use tabs/ 4 spaces.
even though its pure C, this might give you some hints.
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#define MAX_LINE_CHARS 1024
void read_numbers_from_file(const char* file_path)
{
//holder for the characters in the line
char contents[MAX_LINE_CHARS];
int size_contents = 0;
FILE *fp = fopen(file_path, "r");
char c;
//reads the file
while(!feof(fp))
{
c = fgetc(fp);
contents[size_contents] = c;
size_contents++;
}
char *token;
token = strtok(contents, " ");
//cycles through every number
while(token != NULL)
{
int number_to_add = atoi(token);
//handle your number!
printf("%d \n", number_to_add);
token = strtok(NULL, " ");
}
fclose(fp);
}
int main()
{
read_numbers_from_file("path_to_file");
return 0;
}
reads a file with numbers separated by white space and prints them.
Hope it helps.
Cheers