I program which reads the letters and numbers from the input being used. But i dont know how to implement this to a .txt file. This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
int countLetters = 0, countDigits = 0;
cout << "Enter a line of text: ";
cin.get(ch);
while(ch != '\n'){
if(isalpha(ch))
countLetters++;
else if(isdigit(ch))
countDigits++;
ch = toupper(ch);
cout << ch;
//get next character
cin.get(ch);
}
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}
I made a mistake in my HW I was suppose to count the words instead of letters from the .txt file. Im having trouble counting words because I get confused with the space between words. How could I change this code to count the words instead of letters? I really appreciate the help.
This code counts each word separately. If the first character of a "word" is a number, it assumes the entire word is numeric.
#include <iterator>
#include <fstream>
#include <iostream>
int main() {
int countWords = 0, countDigits = 0;
ifstream file;
file.open ("your_text.txt");
string word;
while (file >> word) { // read the text file word-by-word
if (isdigit(word.at(0)) {
++countDigits;
}
else {
++countWords;
}
cout << word << " ";
}
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
int countLetters = 0, countDigits = 0;
ifstream is("a.txt");
while (is.get(ch)){
if(isalpha(ch))
countLetters++;
else if(isdigit(ch))
countDigits++;
ch = toupper(ch);
cout << ch;
}
is.close();
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}
Related
I'm trying to read a csv file and write it into an array. I have an error in getline. the error is:
no instance of overloaded function "getline" matches the argument list.
what's wrong?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream Input("M.A.csv");
int index = 0;
const int Num = 57;
int shift_counter = 0;
char Data[Num][6];
if (Input.is_open()) {
cout << '\n' << '\t' << "Anslyzing file..." << endl << '\n';
while (Input) {
getline(Input, Data[index]);
cout << Data[index][2];
cout << ++index << endl;
if (++index == Num) {
index = 0;
shift_counter++;
cout << '\n' << '\t' << "*** shift_counter is :" << shift_counter << '\n' << '\t';
}//if (++index == Num)
}//while (Input)
/*for (int i = 1,j=1; i <= Num ,j<=6 ; i++, j++) {
Data[i][j]=
}*/
}//if (Input.is_open())
else {
cout << '\n' << '\t' << "No file has been opened" << endl << '\n';
}//else
system("pause");
return 0;
}
The type char has no matter for getline, so why I can't getline?
The function getline() expects the second argument to be a std::string, but you provide a char array. There is no overloaded instance with those types.
I have a programmer for c++ that ask me a file name first, then ask for the search word. the line that contains it should be displayed with its exact line number in front.
for example:
20:XXXXXX.
I have code here. I don't know how to display the line number. please help me.
#include <iostream>
#include <string> //to work with strings
#include <fstream>
using namespace std;
int main()
{
int occurenceNumber = 0;
int counter = 0;
int lineNum;
string fileName;
string toSearch;
string lineRead;
ifstream inputFile;
cout << "Enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if(!inputFile){
cout << "Error opening file, or file doesn't exist!";
cout << "Try again!\n";
return 0;
}
cout << "Enter string to search for: ";
cin >> toSearch;
cin.ignore();
while(getline(inputFile, lineRead))
{
if(lineRead.find(toSearch, 0) < lineRead.length())
{
occurenceNumber++;
cout << lineRead << endl;
}
}
cout << toSearch << " was found " << occurenceNumber;
cout << " times. \n";
inputFile.close();
return 0;
}
You set a counter variable. You just forgot to use it. This is the while loop in your code with that counter variable that you defined but forgot to use.
If you place the counter++ at the beginning of that while loop, the first line is line 1. On the other hand, if you place it at the end of the loop, the first line is line 0.
while(getline(inputFile, lineRead))
{
counter++;
if(lineRead.find(toSearch, 0) < lineRead.length())
{
occurenceNumber++;
cout << counter << ":" << lineRead << endl;
}
}
I am new to c++ and am trying to do a string search for 2 words(double and triple) in a file and print the line on which they are found. Some lines only have the word "double" and some only have the word "triple".
The code doesn't seem to output the words, it just prints the last line at the end of the loop.
I forgot to add that I need to print the first element of the line on which the word is found, I am able to locate the line where the word is found, however, it doesnt seem to print the first element on the file.
Here is my code.
int main(int argv, char *argc[]){
const string filen("test.txt");
ifstream inFile(filen.c_str());
string line = "";
char IDList[10];
string ID = "";
char* double_word = "double"; // test variable to search in file
char* triple_word = "triple";
stringstream ss;
string word = "";
unsigned int currentLine = 0;
// iterate through each line and check if the words double or triple exist.
while(getline(inFile, line)){
currentLine++;
if (line.find(double_word) != string::npos) {
cout << "found the word \"double\" on line: " << currentLine << endl;
// this part takes the input file and reads the first character of the line i.e. the ID and adds it to the IDList
// string array.
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else if(line.find(triple_word) != string::npos){
cout << "found the word \"triple\" on line: " << currentLine << endl;
// now take the id of this file and add it to a different queue.
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else if(line.find(double_word) && line.find(triple_word) != string::npos){
cout << "Found both words double and triple in line: " << currentLine << endl;
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else{
cout << "neither word found, moving to next line" << endl;
}
}
inFile.close();
cout << "Id's added to the queue" << word << endl;
return 0;
}
I think you can simplify your code and write something like this:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using std::string;
using std::vector;
using std::cout;
using std::cin;
int main(int argc, char* argv[]) {
const string filen("test.txt");
std::ifstream inFile(filen.c_str());
string line;
string double_word = "double"; // test variable to search in file
string triple_word = "triple";
vector<string> IDs;
unsigned int currentLine = 0;
// iterate through each line and check if the words double or triple exist.
while(getline(inFile, line)){
currentLine++;
bool found_d_word = line.find(double_word) != string::npos;
bool found_t_word = line.find(triple_word) != string::npos;
if ( found_d_word && !found_t_word )
cout << "found the word \"double\" on line: " << currentLine << '\n';
if ( found_t_word && !found_d_word )
cout << "found the word \"triple\" on line: " << currentLine << '\n';
if ( found_d_word && found_t_word )
cout << "Found both words double and triple in line: " << currentLine << '\n';
if ( found_d_word || found_t_word ) {
std::istringstream ss{line};
string ID;
ss >> ID;
cout << "File Id: " << ID << '\n';
// my guess: store all the IDs in one vector
IDs.push_back(ID);
} else {
cout << "neither word found, moving to next line\n";
}
}
inFile.close();
return 0;
}
One of the problems with your code is that you first read a line of the input file (with getline), put that in a string and then, when the word "double" or "triple" is found in the string, you try to read the ID from the file while you should read it from the same string.
Try this,
#include "iostream"
#include "string"
#include "sstream"
#include "fstream"
using namespace std;
int main()
{
stringstream y; string x; int lc=0, id;
ifstream fin("file.txt");
while (getline(fin, x))
{
++lc;
y.str(x);
y >> id;
bool d=x.find("double")!=string::npos;
bool t=x.find("triple")!=string::npos;
if (d and t)
cout << "found words double and triple on line " << lc
<< ", id is " << id << endl;
else if (d)
cout << "found word double on line " << lc
<< ", id is " << id << endl;
else if (t)
cout << "found word triple on line " << lc
<< ", id is " << id << endl;
}
}
Not sure why my loop isn't working, it keeps sticking every time I try an input :/
Am hoping for an onput that just shows the count of the diffent types which I've listed.
#include <iostream>
#include <string>
#include <iomanip>
#include <cctype>
using namespace std;
int main() {
char ch;
int puncCount = 0;
int letterCount = 0;
int digitCount = 0;
int spaceCount = 0;
cout << "The characters which you'd like!" << endl;
cout << "Type a line with a single 'Q' to stop \n" << endl;
cin.get(ch);
while (ch != 'q')
{
letterCount += isalpha(ch);
puncCount += ispunct(ch);
digitCount += isalnum(ch);
spaceCount += isspace(ch);
}
cout << "Letter count is" << letterCount << endl;
cout << "Puncuation count is" << puncCount << endl;
cout << "Digit count is" << digitCount << endl;
cout << "Space count is" << spaceCount << endl;
return 0;
}
You need to put another call to get input within the loop:
while (ch != 'q')
{
// ...
cin.get(ch);
}
You are not repeating the call to get the characters in the loop. Also, check for 'q' and'Q' if that is your aim.
I am a beginning c++ student and am attempting to write a program that takes a word in a file and indexes it, listing each word only once and displaying the line numbers of every time that word appears. I have tried using a map but i found it impossible to get the line numbers for the words. Instead, I am using a vector of structs that has an integer vector and a string for each word. I am trying to read each word, place it into a stringstream, then output it into the string in the struct. Then I take the line number and push_back it into the vector in the struct. then I save everything to the vector of the struct and try to print out each word associated with the line number vector. I am getting nowhere and would like some help. Itd be much appreciated! Here is my source code:
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <sstream>
#include <vector>
using namespace std;
struct words {
vector<int> lineNumbers;
string word;
};
int main() {
ifstream inFile, testStream;
ofstream outFile;
string temp, choice, inFileName, outFileName, word, trash, word2, tempString;
int idx = 0, count = 0, idxTwo = 0;
bool outputOpened = false;
//map <string,int> wordList;
/map <string,int>::iterator wordIt;
stringstream myStream(ios_base::in| ios_base::out);
vector<words> myIndex;
words data;
for (;;) {
cout << "Options: "<< endl << "1. Index" << endl << "2. Quit" << endl
<< "Please enter an option: ";
getline(cin, temp);
//cin >> temp;
//cin.ignore(8192, '\n');
choice.resize(temp.length());
transform(temp.begin(), temp.end(), choice.begin(), ::toupper);
if (choice.compare("INDEX") == 0 || choice.compare("1") == 0) {
do {
inFileName.clear();
cout << "Index Program" << endl
<< "==============" << endl << endl;
cout << "Input file name: ";
getline(cin, inFileName);
inFile.open(inFileName.c_str());
if(inFile.fail()) {
cout << "Can't open file" << endl;
if(inFile.bad()) {
cout << "Bad" << endl;
}
inFile.clear();
}
}
while (!inFile.is_open());
do {
cout << "Output file name: ";
getline( cin, outFileName);
testStream.clear();
testStream.open(outFileName.c_str());
if(testStream.good()) {
cout << "That file already exists, try again" << endl;
testStream.clear();
testStream.close();
}
else {
testStream.clear();
testStream.close();
outFile.open(outFileName.c_str());
if (outFile.good()) {
outputOpened = true;
}
}
}
while (!outputOpened);
while (getline(inFile, trash)){
count++;
myStream << trash;
//myStream >> tempString;
while(myStream >> data.word) {
data.lineNumbers.push_back(count);
myIndex.push_back(data);
}
}
for (idx = 0; idx < myIndex.size(); idx++) {
outFile << "Word: "<< " "<< myIndex[idx].word << ", ";
for (idxTwo = 0; idxTwo < myIndex[idx].lineNumbers.size(); idxTwo++) {
outFile << "Found on lines " << " " << myIndex[idx].lineNumbers[idxTwo];
}
}
inFile.close();
outFile.close();
}
else if (choice.compare("QUIT") == 0 || choice.compare("2") == 0) {
return 0;
}
else {
cout << temp << " is an unrecognized option, please try again" << endl;
}
}
return 0;
}
Your problem seems to be that you are always appending each word to the vector<words>.
What you probably want, is a map<string, vector<int>>. Use .insert to insert words in to the set, if it already exists then just append the current line number to the value.
For this part of your program:
while (getline(inFile, trash)){
count++;
myStream << trash;
//myStream >> tempString;
while(myStream >> data.word) {
// 2.
// data.lineNumbers.clear();
data.lineNumbers.push_back(count);
myIndex.push_back(data);
}
// 1. add:
// myStream.clear();
}
You are using a global myStream. But the state of this myStream will be in a bad state after processing each line, as it ran out of data. The state mush be cleared for it to work again.
The data is also global, which make the line number for every word to be saved in data.lineNumber, not only the line number of the current word. You may want to clear it at each run.
Here are some issues:
Add myStream.clear(); after the while(myStream >> data.word) loop.
Add "\n" to the end of the following line to print on a new line:
outFile << "Found on lines " << " " << myIndex[idx].lineNumbers[idxTwo]<<"\n";
Also, the following nested loop will not give you correct results. It will grow with line numbers and keep printing "Found on lines":
for (idx = 0; idx < myIndex.size(); idx++) {
outFile << "Word: "<< " "<< myIndex[idx].word << ", ";
for (idxTwo = 0; idxTwo < myIndex[idx].lineNumbers.size(); idxTwo++) {
outFile << "Found on lines " << " " << myIndex[idx].lineNumbers[idxTwo]<<"\n";
}