I have a piece of code I'm running in Cygwin in C++ I'm compiling using
g++ -o program program.cpp
And it is returning an error that reads 'Aborted (core dumped)'. It is intended to take a file name as input through a command line argument, count all the unique words and total words in the file, and prompts the user to input a word and counts how many times the word that they input occurs. It's only intended to use C++ streams for input/output.
#include <fstream>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
string filename;
for( int i = 1; i < argc; i++){
filename+=argv[i];
}
ifstream file;
file.open(filename.c_str());
if (!file)
{
std::cerr << "Error: Cannot open file" << filename << std::endl;
return 1;
}
string* words;
int* wordCount;
int wordLength = 0;
string curWord = "";
bool isWord;
int total = 0;
char curChar;
string input;
while(!file.eof())
{
file.get(curChar);
if (isalnum(curChar)) {
curWord+=tolower(curChar);
}
else if (!curWord.empty() && curChar==' ')
{
isWord = false;
for (int i = 0; i < wordLength; i++) {
if (words[i]==curWord) {
wordCount[i]++;
isWord = true;
total++;
}
}
if (!isWord) {
words[wordLength]=curWord;
wordLength++;
total++;
}
curWord="";
}
}
file.close();
// end
cout << "The number of words found in the file was " << total << endl;
cout << "The number of unique words found in the file was " << wordLength << endl;
cout << "Please enter a word: " << endl;
cin >> input;
while (input!="C^") {
for (int i = 0; i < wordLength; i++) {
if (words[i]==input) {
cout << wordCount[i];
}
}
}
}
You never allocated any space for words and wordCount to point to. It should be:
#define MAXWORDS 1000
string *words = new string[MAXWORDS];
int *wordCount = new int[MAXWORDS];
and then at the end of the program you should do:
delete[] wordCount;
delete[] words;
or you can allocate a local array:
string words[MAXWORDS];
int wordCount[MAXWORDS];
But you could do it more simply by using std::map to map the string to a count. This will automatically grow as needed.
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'm trying to read a file called numbers.txt and insert the integers into an array. My code outputs only the last integer in the file.
//numbers.txt
1
10
7
23
9
3
12
5
2
32
6
42
My code:
int main(){
ifstream myReadFile;
myReadFile.open("/Users/simanshrestha/Dev/PriorityQueue/PriorityQueue/numbers.txt");
char output[100];
int count = 0;
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
//cout<< output << endl;
count++;
}
for(int i=0;i<count;i++)
{
cout << output[i];
}
cout<<endl;
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}
int main()
{
std::ifstream myReadFile;
myReadFile.open("/home/duoyi/numbers.txt");
char output[100];
int numbers[100];
int count = 0;
if (myReadFile.is_open())
{
while (myReadFile >> output && !myReadFile.eof())
{
numbers[count] = atoi(output);
count++;
}
for(int i = 0; i < count; i++)
{
cout << numbers[i] << endl;
}
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}
try this.
atoi is a function Convert a string to an integer.
you can try this also: same as the bottom
basically you need to define a "temp" or holder variable to store your data. and anything inside a loop stays in that loop cause of scope resolution, and overriding data each time you store it since it doesn't exit at all.
Hope this helps!
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
const string FILE = "your file name here";
int main()
{
ifstream myReadFile;
myReadFile.open(FILE);
char output[100];
int numbers[100];
int count = 0;
if (myReadFile.is_open()){
while (myReadFile >> output && !myReadFile.eof()) //not stopping until we reach end of file
{
numbers[count] = atoi(output); //converts string to int
count++;
}
for(int i = 0; i < count; i++)
{
cout << numbers[i] << endl;
}
}
cout << "Number of lines: " << count+1 << endl; //total number of lines in file
myReadFile.close();
else{ cout << "Error: File name not loaded" << endl;}
return 0;
}
May I hazard a guess that your code is getting the sum of all the numbers and it is saved in the 1st element of your array?
May I also guess you want the number of the first line in the text file to be saved in the first element of the array? 2nd line in 2nd element so on and so forth?
If so, the following code might need updating:
myReadFile >> output;
to
myReadFile >> output[count];
I'm quite sure this will work in C and assume this would work in C++ too
updated:
another thing to add is to have 2D array like this:
char output[100][5]; //assuming our number is at most 5 char long
This program should read a paragraph from a text file provided by the user and then store each line in a ragged char array and count the total number of words and lines of the paragraph then display the result.
I can't figure out why does the number of lines keep giving me the result of 3
and why the number of words is always missing 2 words.
please help and keep in mind that I'm no professional just started learning c++ recently.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
ifstream infile;//declarations
char filename[45];
char **data = 0;
char **temp = 0;
char *str = 0;
char buffer[500], c;
int numoflines = 0, numofwords = 0;
cout << "Please enter filename: ";//prompt user to enter filename
cin >> filename;
infile.open(filename);//open file
if (!infile)//check if file was successfully opened
{
cout << "File was not successfully opened" << endl << endl;//display error message
return 0;
} //end of if
data = new char*[numoflines];
while (!infile.eof())
{
temp = new char*[numoflines + 1];
for (int i = 0; i < numoflines; i++)
{
infile.getline(buffer, 500);//read line
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
str = new char[strlen(buffer) + 1];//allocate a dynamic array
strcpy(str, buffer);
data[i] = str;
temp[i] = data[i];
}//end of for
infile.getline(buffer, 500);
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
temp[numoflines] = new char[strlen(buffer) + 1];
strcpy(temp[numoflines], buffer);
delete[] data;
data = temp;
numoflines++;
}
cout << "Number of words: " << numofwords << endl;
cout << "Number of lines: " << numoflines << endl;
return 0;
}
The concept of number of lines is a viewing concept only. It's not encoded into the file. The following single paragraph can be displayed on one line or 16 lines depending upon the size of the editor window:
If you wanted to specify a char width of the window, lines could be calculated from that, but as is, paragraphs and wordcount are as good as you will do. And given a successfully opened ifstream infile that is fairly simple to obtain:
auto numoflines = 0;
auto numofwords = 0;
string paragraph;
while(getline(infile, paragraph)) {
numofwords += distance(istream_iterator<string>(istringstream(paragraph)), istream_iterator<string>());
++numoflines;
}
cout << "Number of words: " << numofwords << "\nNumber of lines: " << numoflines << endl;
NOTE:
Visual Studio supports inline construction of an istringstream so if you're not using that you'll need to construct on a separate line.
I'm trying to create a program that reads in numbers from a file into an array, reverse the order of the numbers in the array and then outputs those reversed numbers into a different file. I was able to get the program to work when I already knew how many numbers were in the file but I am having difficulty when I switch my loop to trying to detect the EOF(End of file). When I run this code it will print two of the numbers from the file and the rest are garbage values. Any Help?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int NUMS = 5;
void reverseArray(int number[], int first, int last)
{
int temp;
if (first >= last)
{
return;
}
temp = number[first];
number[first] = number[last];
number[last] = temp;
reverseArray(number, first + 1, last - 1);
}
int main()
{
//Create file objects
ifstream inputFile;
ofstream outputFile;
string inputName;
string outputName;
//Prompt user for file names
cout << "What is the name of the input file?" << endl;
getline(cin, inputName);
cout << "What would you like the output file to be called?" << endl;
getline(cin, outputName);
//open user named files
inputFile.open(inputName);
outputFile.open(outputName);
int numsFromFile;
int numbers[NUMS];
int fileCount = 0;
/*
//read in numbers from a file ********THIS WORKS BUT WHEN I CHANGE IT BELOW IT DOES NOT******
for (int count = 0; count < NUMS; count++)
{
inputFile >> number[count];
}
*/
//Try to read numbers in detecting the EOF
while (inputFile >> numsFromFile)
{
inputFile >> numbers[fileCount];
fileCount++;
}
//print numbers to screen
for (int count = 0; count < fileCount; count++)
{
cout << numbers[count] << endl;
}
//reverse array
reverseArray(numbers, 0, 4);
cout << "Reversed is: " << endl;
//print reversed array
for (int count = 0; count < NUMS; count++)
{
cout << numbers[count] << endl;
}
//output numbers to a file
for (int count = 0; count < NUMS; count++)
{
outputFile << numbers[count] << endl;
}
outputFile.close();
inputFile.close();
return 0;
}
There is a bug in the lines:
while (inputFile >> numsFromFile)
{
inputFile >> numbers[fileCount];
fileCount++;
}
You end up reading and discarding the 1st number, the 3rd number, the 5th number, etc. Change it to:
while (inputFile >> numsFromFile)
{
numbers[fileCount] = numsFromFile;
fileCount++;
}
I open a txt file using argc, argv, and getline. I did that properly, but now I have to get the number of words per line (the number of lines is not known before) and I must output them in reverse. Meaning from the bottom line to the top line. Any help is appreciated. This code outputs the number of words in the file:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
if(argc < 1){
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if(ifile.fail()){
cerr << "Could not open file." << endl;
return 1;
}
int n;
ifile >> n;
cout << n;
int numberOfWords = 0;
string line;
for(int i = 0; i <= n; i++){
getline(ifile, line);
cout << line << endl;
}
size_t i;
if (isalpha(line[0])) {
numberOfWords++;
}
for (i = 1; i < line.length(); i++) {
if ((isalpha(line[i])) && (!isalpha(line[i-1]))) {
numberOfWords++;
}
}
cout<<"The number of words in the line is : "<<numberOfWords<<endl;
return 0;
}
To find the number of words per line you would use std::getline() to iterate over each line and use std::stringstream to extract each chunk of whitespace-separated input. Then you would iterate over each chunk of input and check to see if each character is alphabetic:
int numberOfWords = 0;
for (std::string line, word; std::getline(ifile, line); )
{
std::istringstream iss(line);
while (iss >> word)
{
bool alpha = true;
for (char c : word)
if (!std::isalpha(c)) alpha = false;
if (alpha) ++numberOfWords;
}
std::cout << "Number of words on this line: " << numberOfWords << std::endl;
numberOfWords = 0;
}