I am trying to make a program that reads a line from tst.txt using getline function. However when I try to get the substrings from it, I get an error that says method substr could not be resolved.
My code is the following.
#include <iostream>
#include <fstream>
#include <string>
#include <istream>
#include <sstream>
#include <stdlib.h>
using namespace std;
int main () {
string line;
string substr(int a, int b);
string name[15];
int a[15];
int b[15];
ifstream myfile ("tst.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
int i;
getline (myfile,line);
a[i]= myfile.substr(4,2);
name[i]= myfile.substr(18,15);
b[i]= myfile.substr(36,1);
i=i+1;
cout << a[i] <<" "<< b[i] << " "<< name[i] << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
As mentioned you can't call substr() with a std::ifstream. What you probably meant was to take the parts from the line string read in
a[i]= stoi(line.substr(4,2));
name[i]= line.substr(18,15);
b[i]= stoi(line.substr(36,1));
Also note you'll need to convert the substrings extracted to a number (instead of assigning them directly), hence I have added the stoi().
As also mentioned in the comments on your question, you should do better error checks, and initialize all of your variables properly.
Your while() loop can simply be rewritten as
while (getline (myfile,line)) {
// ...
}
The surrounding if() block
if (myfile.is_open()) {
// ...
}
can be omitted.
You actually prototype a function at line :
string substr(int a, int b);
But never implement it.
What is the point of this line anyways ?
Just remove it, you never call this substr function. The only substr function you call is
std::ifstream::substr
http://www.cplusplus.com/reference/string/string/substr/
Related
I am new to passing values to functions, please guide me what I am doing wrong here, thanks!
The question: Write a C++ program in which, read a c-string sentence
one by one from a file “sentence .txt”. Now your task is to break each
word of sentence into another c-string word, now write that word into
a file “word.txt”. Note : You must create atleast 1 function to
separate the words from sentence, you cannot use strings.
#include <iostream>
#include <fstream>
using namespace std;
char sentence2word(char array[100])
{
ofstream fout2;
fout2.open("word.txt");
fout2 << array << endl;
return array[100];
}
int main()
{
ifstream fin;
fin.open("sentence.txt");
char array[100];
fin >> array;
cout << "Output successful!";
sentence2word(array);
return 0;
system("pause");
}
The following program show how to get started with reading and writing from/into text files in C++. This is just to get you started and in practice i use std::string and std::istringstream to do this but in your note it is written that we cannot use strings so i did not use std::string. The program reads line by line from an input.txt file and write word by word into an output.txt file.
#include <iostream>
#include <fstream>//needed to read/write files
#define MAX_NUMBER_OF_CHARACTERS 500
using namespace std;
//function that writes lines word by word into output.txt
void writeWordByWord(std::ofstream &m_outFile, char (&lineArg)[MAX_NUMBER_OF_CHARACTERS])
{ int i = 0;
while(lineArg[i] != '\0')
{
if(lineArg[i] != ' ')
{m_outFile << lineArg[i];
//std::cout<< lineArg[i]<<" wrote"<<std::endl;
++i;
}
else{
m_outFile << '\n';
++i;
}
}
//m_outFile << '\n';
}
int main()
{
cout << "Hello World" << endl;
char line[MAX_NUMBER_OF_CHARACTERS];
std::ifstream inFile("input.txt");
std::ofstream outFile("output.txt");
while(inFile.getline(line, MAX_NUMBER_OF_CHARACTERS, '\n'))
{
std::cout<<line<<std::endl;
writeWordByWord(outFile, line);
}
inFile.close();
outFile.close();
return 0;
}
This is my code.
I am supposed to count the number of 'duck' in a txt file and print string like "There were 2 ducks in animals01.txt"
Now I get no error and nothing return.
Please tell me what's wrong?
#include <iostream> // for printf()
#include <cstdlib> // for exit(), perror()
#include <fstream> // for ifstream
using namespace std;
int main(int argc, char *argv[])
{
if (argc!=2) {
// if argc is not 2, print an error message and exit
cerr << "Usage: "<< argv[0] << " inputFile" << endl;
exit(1); // defined in cstdlib
}
return 0;
int num = 0;
ifstream ifs;
ifs.open(argv[1]);
string line;
do{
getline(ifs, line);
cout<<line<<endl;
if(line == "duck"){num++;}
}while(!ifs.eof());
cout<<"There were"<<num<<"ducks in"<<argv[1]<< endl;
}
You have the line return 0; before you actually did anything, and when you return main() the program is terminated.
By the way, don't use while(!ifs.eof()) because the eof flag only gets set at the first attempt to read past the end of the file, not when you read exactly to the end of the file due to a line break at the end. Do something like this. Also, fix your indenting as it is very misleading.
Read the file word by word.
Example:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string str, strToSearch = "ducks";
int wordCount = 0;
ifstream fin("thisfile.txt");
while (fin >> str) // Will read up to eof() and stop at every whitespace it hits. (like spaces!)
{
if(str==strToSearch)
wordCount++;
}
fin.close();
cout<<"There were"<<wordCount<<"ducks in thisfile.txt"<<endl;
return 0;
}
I'm trying to make a program that will receive a string and output an uppercase version of that. My code works, however once it loops through the string and changes it, it immediately crashes and I'm not completely sure why. Here are my two pieces of code.
/*This program is to intended to receive a string and return a version of it in all upper case*/
#include <iostream>
#include <string>
#include <locale>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++;)
std::cout << std::toupper(str[i]); //A loop which goes through each digit of the string
break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
/*This program calls a function to make a string in upper case*/
#include <iostream>
#include <string>
#include <sstream>
#include <locale>
#include "toUpper1.h" //Calls the header file which contains the loop
using namespace std;
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
cout<<toUpper(input); //The command that causes the user input string to be transformed into upper case
return 0;
}
You can make string to uppercase using code bellow
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Or use like this
#include <algorithm>
#include <string>
std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
You are breaking the function without returning anything. Use {} to close for loops if you want to use break
prog.cpp:16:5: error: break statement not within loop or switch
break;
Also your for loop has an extra ; at the end.
std::cout and std::toupper are useless as you are already including namespace std;
and why are you using break;? there is no need of it.
just write
for (int i=0; i<str.length(); i++)
cout << toupper(str[i]);
Remove break;
You are not transforming the string, you are outputting its transformation in the function.
instead of
std::cout << std::toupper(str[i]);
use
str[i]=std::toupper(str[i]);
And move all printing out of the function. Changing the string doesn't include printing!
Notice the #bbdude95 answer, too.
edit
Instead of
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input;
use
char input[256];
cout << "Please type in a word:\n>";
cin.getline( input, 256, '\n' );
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++)
str[i] = std::toupper(str[i]); //A loop which goes through each digit of the string
//break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
//The command that causes the user input string to be transformed into uppe case
cout << toUpper(input);
cout << std::endl << "The original string is" << input << std::endl;
return 0;
}
EDIT: Note that keeping the function signature as above (string toUpper ( string str), as were required), we are making some extra string copies, and, most important: we are NOT modifying the original string (excute the code and see the result of last cout.
In c++ how would I read a text file containing 3 float variables not as string types, but as float variable types for re-use by a program.
I was trying to use fscanf function and having results of it only reading in the first line of the file. How do I tell it to use delimiters such as \n end of line and have it continue to process the rest of the file?
Thanks.
#include <cstdlib>
#include <math.h> //Include math functions
#include <iostream> //Stream to allow input/output
#include <fstream> //Stream class to read/write files
using namespace std;
string line = "0.0";
char str [80];
float f;
FILE * pFile;
int main () {
pFile = fopen ("C:\\Users\\Brian\\Documents\\NetBeansProjects\\CppApplication_2\\init_temps.txt","r");
fscanf (pFile, "%f", &f);
cout << f;
return 0;
}
Based on your code, it seems you are only reading the first number. You should iterate 3 times:
int i;
for(i = 0; i < 3; i++)
{
fscanf(pFile, "%f", &f);
cout << f << endl;
}
or better yet check for fscanf()'s return value to better decide if you've read it all.
On another note, you should learn to use local variables instead of global variables, unless there's really a need to.
Hope this helped.
floats.text
5.5
2.2
1.1
read.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
float sum = 0;
ifstream myfile ("floats.text");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
sum += ::atof(line.c_str());
}
myfile.close();
}
cout << sum << endl;
return 0;
}
result
./a.out
>> 8.8
I have a problem trying to count words inside of a vector. A vector holds every line from a file as an object. v[0] is the first line, v[1] is the second line, so on.
For my countWords() function, it only works for counting v[0]. Any object past that is ignored or missed some how. Any ideas? Thanks in advance.
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int countWords(vector<string> v)
{
stringstream ss;
string word;
int count = 0;
for(int i = 0; i < v.size(); i++) {
ss.str(v[i]);
while (ss >> word)
count++;
}
return count;
}
void readFile(string filename,vector<string> &v)
{
fstream file;
string line;
file.open(filename,ios::in);
while(getline(file,line)) { //Reads the file line by line ...
if(line == "") //... ignoring any empty lines ...
continue;
v.push_back(line); //... and puts them into our vector.
}
file.close();
}
int main(int argc,char* argv[])
{
if (argc != 2) { //Terminate unless the user enters -ONE- entry.
cout << "Usage: " << argv[0] << " <filename>" << endl;
exit(1);
}
string filename = argv[1];
vector<string> fileContents;
readFile(filename,fileContents);
cout << countWords(fileContents) << endl;
}
As an alternative to RichieHindle's answer, this works too. Just have the stringstream scope local to the for loop and it will reset properly.
int countWords(vector<string> v)
{
string word;
int count = 0;
for(int i = 0; i < v.size(); i++) {
stringstream ss(v[i]);
while (ss >> word)
count++;
}
return count;
}
Before you reuse stringstream you must do
ss.clear();
after your while loop.
You could also declare it inside the for() loop, but then it would be reinitialized again. For readabillity, this might be better. Performancewise it could make a difference.
I bet ss goes into an error state when you've exhausted it for the first time and doesn't reset just because you call str.
Declare ss inside the for loop and pass the string directly to the constructor. This avoids such problems.
In general, you have the bad habit of declaring your variables in a bunch instead of closest to where you need them, and not using constructors. For example, you could pass the filename to fstream's constructor instead of calling open. And you could use ifstream so you don't need the second argument.