I am trying to read lines from a .txt file and print them out using std::cout. My code is posted below, but currently is not passing any lines to the vector during the while loop. Where did I go wrong?
int main(int argc, const char * argv[]) {
std::ifstream input("input1.txt");//(argv[1]);
if (!input.good()) {
cerr << "Can not open the grades file "; //<< argv[1] << "\n";
return 1;
}
std::vector<string> art;
string x; // Input variable
// Read the scores, appending each to the end of the vector
cout << "Start While:"; //For Debugging Purposes
while (getline(input, x)) {
art.push_back(x);
}
for (int i=0; i<art.size(); i++) {
cout << art[i] << "\n";
}
return 0;
}
Turns out Xcode was just being difficult. After moving a few files around and running it in the compiler it worked.
Related
So, I have a program that I am running through a command line on a raspberry pi on C++. I know how I can pass in the command line arguments already, but I need to pass it using cin, but I'm not able to get it to work.
Normally I would use args, and use a format on the command line such as ./program filename, but I have to use this format ./program < filename to redirect the filename to the program through stdin for this assignment. My instructor has told me to use cin, but no matter what I do, it will not open the file.
int main(int argc, char *argv[])
{
cout << "Matching Brackets: NAME" << endl;
string line;
string fname;
cin >> fname;
ifstream myfile;
myfile.open(fname);
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
int num = valid(line);
if(num >= 0)
cout << valid(line) << " ";
}
}
cout << endl;
myfile.close();
return 0;
}
I'm trying to get the cin to take the actual filename of a text file and use that in fstream to open the file and read through it to perform the operations, but I can't get it to open in that method, and I haven't been able to find anything about doing it that way.
When you use your program as
./program < filename
you only need to worry about reading content from stdin/std::cin.
main can be simplified to:
int main(int argc, char *argv[])
{
cout << "Matching Brackets: NAME" << endl;
string line;
while ( getline (std::cin, line) )
{
int num = valid(line);
if(num >= 0)
cout << num << " "; // No need to call valid(line) again;
}
cout << endl;
return 0;
}
I'm currently beginning on C++ and trying to make a function that can open a .txt file, read it, and save its words in an array (each word being a protein sequence).
Unfortunately I don't succeed at calling the argument containing the name of the file (argv[1]) in the function.
Can anyone spot errors in my code or in the way I implemented this ?
Thanks in advance, you will find the code and the error messages below :
Libraries
So here are my librairies and 'shortcuts'.
// Librairies
#include <iostream>
#include <string>
#include <fstream>
// Alias
using std::cout;
using std::endl;
using std::string;
The function
Now this is the function, note that filename is supposed to be a string containing argv[1] (the name of a .txt file specified at execution) :
string SequenceChoice(int n, string filename); // Function returning a string
std::ifstream sequenceFile (filename); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}
sequenceFile.close();
cout<< "File closed"<<endl;
}
else
{
cout << "Error: Cannot open file" << endl;
}
return allchains[n]; // returns the 'n'th word (n being specified when calling the function
// end of the function
Main
Now the main function, I'm not sure if doing string filename = argv[1] works, but I get less errors when I keep this step instead of putting argv[1] as an argument of my SequenceChoice() function.
int main(int argc, char *argv[]) {
if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, filename ) << endl; // I expect it to give me the 3rd word of a .txt file for example.
}
else
{
cout << "Error : No file" << endl;
}
return 0;
}
The error message I get
Error message
The link above is a picture of the error message I get when I compile, I've been searching for hours on the internet how to resolve this, unfortunately I could'nt manage to have the code working. There's probably an error of type with the way I deal with argv[], but I failed at solving it so any help and comments would be greatly appreciated.
Please try changing following line
string SequenceChoice(int n, string filename); // Function returning a string
to
string SequenceChoice(int n, string filename) { // Function returning a string
You are trying to write a function but the ; is terminating your function and body is not starting. It should work. Also please read a book carefully.
This page lists very good books for all experience levels.
Try this :
string SequenceChoice(int n, string filename)
{
std::ifstream sequenceFile (filename); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}
ifs.close();
cout<< "File closed"<<endl;
}
else
{
cout << "Error: Cannot open file" << endl;
}
return allchains[n];
}
Here is fully functioning code:
You can compare it with yours.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string SequenceChoice(int n, string filename){ // Function returning a string
std::ifstream sequenceFile (filename); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}
sequenceFile.close();
cout<< "File closed"<<endl;
return allchains[n]; // returns the 'n'th word (n being specified when calling the function
}
else
{
cout << "Error: Cannot open file" << endl;
}
return NULL;
// end of the function
}
int main(int argc, char *argv[])
{
if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, filename ) << endl; // I expect it to give me the 3rd word of a .txt file for example.
}
else
{
cout << "Error : No file" << endl;
}
}
Thanks to your answers I managed to solve my problem, apart from some syntax errors in the code the argument filename in the function was a string, and as argv[] is an array of pointers. So it just couldn't work to consider them as the same type.
Here is a working version of the function, for those it could help :
string SequenceChoice(int n, char* argv[])
{
std::ifstream sequenceFile (argv[1]); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<< " .File opened. \n" <<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
cout << " " << i << " chains in the .txt file : \n" << endl;
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << " --- Chain "<< i + 1 << " --- : " << allchains[i] << endl;
i++;
}
sequenceFile.close();
cout << "\n .File closed. \n" << endl;
return allchains[n];
}
else
{
cout << "Error: Cannot open file" << endl;
return NULL;
}
}
And finally the new main function :
int main(int argc, char *argv[]) {
if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, argv ) << endl; // Shows the 3rd word of the file, as an example.
}
else
{
cout << "Error : No file" << endl;
}
return 0;
}
Thanks for your help and have a great day !
This program takes in an input, write it on a file character by character, count the amount of characters entered, then at the end copy it to an array of characters. The program works just fine until we get to the following snippet file.getline(arr, inputLength);. It changes the .txt file data and returns only the first character of the original input.
Any ideas?
#include <iostream>
#include <fstream>
using namespace std;
int getLine(char *& arr);
int main() {
char * arr = NULL;
cout << "Write something: ";
getLine(arr);
return 0;
}
int getLine(char *& arr) {
fstream file("temp.txt");
char input = '\0'; //initialize
int inputLength = 0; //initialize
if (file.is_open()) {
while (input != '\n') { //while the end of this line is not reached
input = cin.get(); //get each single character
file << input; //write it on a .txt file
inputLength++; //count the number of characters entered
}
arr = new char[inputLength]; //dynamically allocate memory for this array
file.getline(arr, inputLength); //HERE IS THE PROBLEM!!! ***
cout << "Count : " << inputLength << endl; //test counter
cout << "Array : " << arr << endl; //test line copy
file.close();
return 1;
}
return 0;
}
I see at least two problems with this code.
1) std::fstream constructor, by default, will open an existing file. It will not create a new one. If temp.txt does not exist, is_open() will fail. This code should pass the appropriate value for the second parameter to std::fstreams constructor that specifies that either a new file needs to be created, or the existing file is created.
Related to this: if the file already exists, running this code will not truncate it, so the contents of the file from this program's previous run will have obvious unexpected results.
2) The intent of this code appears to be to read back in the contents temp.txt that were previously written to it. To do that correctly, after writing and before reading it is necessary to seek back to the beginning of the file. This part appears to be missing.
There is no need in dynamic allocation because the std library functions get confused with mixed arguments such as cstring and pointer to cstring.I tested this code in Visual Studio 2015 compiler. It works good. Make sure to include all of the needed libraries:
#include <iostream>
#include <fstream>
#include<cstring>
#include<string>
using namespace std;
void getLine();
int main() {
cout << "Write something: ";
// no need to pass a pointer to a cstring
getLine();
system("pause");
return 0;
}
void getLine() {
char input[100]; // this is a cstring with
//a safe const number of elements
int inputLength; //to extract length of the actual input
//this function requires cstring as a first argument
// and constant length as a second
cin.get(input, 100, '\n'); //get each single character
//cast streamsize into int
inputLength = static_cast<int>(cin.gcount());
//testing input
cout << "Input: \n";
for (int i = 0; i < inputLength; i++)
{
cout << input[i];
}
cout << endl;
char arr[100];
strcpy_s(arr, input);
cout << "Count : " << inputLength << endl; //test counter
cout << "Array : " << endl; //test line copy
for (int i = 0; i < inputLength; i++)
{
cout << arr[i];
}
cout << endl;
// write cstring to a file
ofstream file;
file.open("temp.txt", ios::out);
if (file.is_open())
{
//write only what was entered in input
for (int i = 0; i < inputLength; i++)
file << arr[i];
file.close();
}
else cout << "Unable to open file";
}
This program is supposed to tell the user how many words and lines are in their program (text file only). The two functions that I have written both work, except the num_of_lines function is counting one more line than is correct every time and the num_of_words function is off by about 300 words every time. Not sure what I am doing wrong here. Any help will be greatly appreciated, thanks. I copy and pasted an output after my code and compared it to wc.
#include <iostream>
#include <fstream>
#include <cctype>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_words(string name)
{
int cnt2 = 0;
ifstream iwords;
iwords.open(name);
string w;
if(iwords.is_open())
{
while(iwords >> w)
{
cnt2++;
}
}
else cerr <<"can not open" + name << endl;
iwords.close();
return(cnt2);
}
int num_of_lines(string name)
{
int cnt3 = 0;
string line;
ifstream ilines;
ilines.open(name);
if(ilines.is_open())
{
while(getline(ilines, line))
{
cnt3++;
}
}
else cerr <<"can not open" + name << endl;
ilines.close();
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(string name);
if(argc == 1)die("usage: mywc your_file");
string file;
file = argv[1];
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int b;
b = num_of_words(file);
cout <<"Words: " << b << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Zacharys-MBP:c++ Zstow$ my sample.txt
Chars: 59526
Words: 1689
Lines: 762
Zacharys-MBP:c++ Zstow$ wc sample.txt
761 2720 59526 sample.txt
Zacharys-MBP:c++ Zstow$
Most files (especially programs) will end in a new line. You may not see this in your editor but it is probably there. You will have to check the last line to see if it actually contains any content, or if it is empty.
The istream operator (>>) will detect any group of characters between whitespace to be a "word." So if you're parsing programs, you may have:
for(int i=1; i<73; i++)
The istream operator will see 4 words: [for(int, i=1;, i<73;, i++)]
I'm reading the individual lines from a text file and attempting to print them out on individual lines in the command prompt, but the text just flashes really quickly and disappears.
I is set to the number of lines in readable.txt
cout << "These are the names of your accounts: " << endl;
for (int b = 1; b <= i; b++)
{
fstream file("readable.txt");
GotoLine(file, b);
string line;
file >> line;
cout << line << endl;
}
cin.ignore();
break;
Any help would be greatly appreciated.
error:
Opening a fstream inside a loop? that is suicide, your fstream is always the same why are you opening it for every iteration?
The text probably disappears because your program reaches the end and auto exits you should make him wait before the break or before it reaches the end
You don't need to reopen file every time and invoke GotoLine(file, b); you can open it once outside the for loop and read strings via std::getline(file, line).
If you want to watch the output, insert system("pause") just after the for loop. If you want to pause input after each line, insert getchar() in the end of the for loop (inside of it)
Firstly avoid opening a file inside a for loop. You are doing a lot of mess here.
Try this code
std::ifstream file("readable.txt");
file.open("readable.txt");
if(file.fail())
{
std::cout << "File cannot be opened" << std::endl;
return EXIT_FAILURE;
}
std::string line;
while std::getline(file, line) // This line allows to read a data line by line
{
std::cout << line << std::endl;
}
file.close();
system("PAUSE"); // This line allows the console to wait
return EXIT_SUCCESS;
The break is nonsense (if the snippet is not in a loop or switch.
My guess for the disappearing text is an interference with a IDE. Try it in a terminal/console.
And as in the other answers, file open should be outside the loop.
#include <iostream>
#include <fstream>
using namespace std;
void GotoLine(fstream &f, int b)
{
char buf [999];
while (b > 0) { f.getline (buf, 1000); b--; }
}
int main ()
{
int i = 5;
cout << "These are the names of your accounts: " << endl;
for (int b = 1; b <= i; b++)
{
fstream fl("readable.txt");
GotoLine(fl, b);
string line;
fl >> line;
cout << line << endl;
}
}