I want to do a read word by word and compare what word with what I have in my struct array. If I don't have one, I want to add in the first empty spot.
#include <iostream>
#include <fstream>
#include <string>
#include<string.h>
using namespace std;
struct cuvinte{
char *cuvant;
int numar;
};
int main()
{
cuvinte multime[100];
ifstream f;
f.open("input.txt");
string str;
while(getline(f,str))
{
char * cuvant = new char[str.size() + 1];
char * abc = new char[str.size() + 1];
copy(str.begin(), str.end(), abc);
cuvant = strtok (abc," ,/_");
while(cuvant!=NULL)
{
for(int i=0;i<10;i++)
{
cout<<cuvant;
if(strcmp(cuvant,multime[i].cuvant)==0)
multime[i].numar++;
else
{
for(int j=0;j<10;j++)
if(multime[j].numar==0)
{
multime[j].cuvant=cuvant;
multime[j].numar=1;
}
}
}
cuvant = strtok ( NULL , " ");
}
}
return 0;
}
Strcmp works infinitely and only takes the first word; I don't know why.
In C++ it should only take a handful of lines:
#include <string>
#include <fstream>
#include <unordered_map>
using WordFrequency = std::unordered_map<std::string, unsigned>;
WordFrequency read_words(std::istream& s) {
WordFrequency wf;
for(std::string word; s >> word;)
++wf[word];
return wf;
}
int main() {
std::fstream f("input.txt");
auto wf = read_words(f);
}
Before using word you may like to lower-case it and remove all punctuation, so that your dictionary doesn't contain separate entries for the same word, e.g. Or, or, or,.
Related
I'm trying to parse a string with spaces into several strings and store them into a list, which consists of strings without any space. I do not know how long the input of the string will me and I have the following code:
#include <bits/stdc++.h>
#include <sstream>
using namespace std;
vector<string> myWords;
vector<char> myBuffer;
int main() {
string mySentence;
getline(cin, mySentence);
int j = 0;
for (int i = 0; i < mySentence.length(); i++) {
if (mySentence[i] != ' ') myBuffer.push_back(mySentence[i]);
else {
myWords.push_back(myBuffer);
myBuffer.clear();
j++;
}
}
return 0;
}
The error in which I'm getting is at myWords.push_back(myBuffer);. How do I get around this?
The problem is that you are trying to push a std::vector<char> where a std::string is expected. So simply change the type of myBuffer to a std::string:
#include <iostream>
#include <string>
int main() {
std::string mySentence;
std::getline(std::cin, mySentence);
std::vector<std::string> myWords;
std::string myBuffer;
for (int i = 0; i < mySentence.length(); i++) {
if (mySentence[i] != ' ')
myBuffer.push_back(mySentence[i]);
else {
myWords.push_back(myBuffer);
myBuffer.clear();
}
}
if (!myBuffer.empty()) {
myWords.push_back(myBuffer);
}
// use myWords as needed...
return 0;
}
That being said, using a std::istringstream would be much simpler, as operator>> reads whitespace-delimited values from a stream for you:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string mySentence;
std::getline(std::cin, mySentence);
std::vector<std::string> myWords;
std::string myBuffer;
std::istringstream iss(mySentence);
while (iss >> myBuffer) {
myWords.push_back(myBuffer);
}
// use myWords as needed...
return 0;
}
Alternatively, let the standard library handle the reading and pushing for you:
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
int main() {
std::string mySentence;
std::getline(std::cin, mySentence);
std::vector<std::string> myWords;
std::istringstream iss(mySentence);
std::copy(
std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter(myWords)
);
// use myWords as needed...
return 0;
}
I dont understand how to compare between string in c++??
string s1="abc";
string s[]={"abc","vsj"};
int length=sizeof(s)/sizeof(s[0]);//length of s
for(int i=0;i<length;i++)
{
if(s[i].compare(s1))
{
cout<<"One of the string equal to s1";
}
}
Is it possible??
Thanks..
std::string overloads operator==. You can compare 2 string using operato==. Also you can use std::vector instead of array. Using c++11:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s1="abc";
vector<string> ss = { "abc", "vsj" };
for (auto &s: ss) {
if (s == s1) {
cout<<"One of the string equal to s1";
}
}
return 0;
}
Using c++98:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s1="abc";
vector<string> ss;
ss.push_back("abc");
ss.push_back("vsj");
for (size_t i = 0; i < ss.size(); ++i) {
if (ss.at(i) == s1) {
cout<<"One of the string equal to s1";
}
}
return 0;
}
compare return the same values as strcmp:
<0 - the first character that does not match has a lower value in ptr1 than in ptr2
0 - the contents of both strings are equal
>0 - the first character that does not match has a greater value in ptr1 than in ptr2
I have written a program to store a text file in vector of characters .
#include<iostream>
#include<fstream>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
vector<char> vec;
ifstream file("text.txt");
if(!file.eof() && !file.fail())
{
file.seekg(0, std::ios_base::end);
std::streampos fileSize = file.tellg();
vec.resize(fileSize);
file.seekg(0, std::ios_base::beg);
file.read(&vec[0], fileSize);
}
int c = count(vec.begin(), vec.end(), 'U');
cout << c;
return 0;
}
I want to count occurrence of "USER" in the text file , but using count i can only count number of characters . How can i count number of occurrences of "USER" in the vector of character?
For example
text.txt
USERABRUSER#$$* 34 USER ABC RR IERUSER
Then the count of "USER" is 4. Words can only be in uppercase.
std::string has a find member function that will find an occurrence of one string inside another. You can use that to count occurrences something like this:
size_t count(std::string const &haystack, std::string const &needle) {
auto occurrences = 0;
auto len = needle.size();
auto pos = 0;
while (std::string::npos != (pos = haystack.find(needle, pos))) {
++occurrences;
pos += len;
}
return occurrences;
}
For example:
int main() {
std::string input{ "USERABRUSER#$$* 34 USER ABC RR IERUSER" };
std::cout << count(input, "USER");
}
...produces an output of 4.
This is how I would do it:
#include <fstream>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
unordered_map<string, size_t> data;
string line;
ifstream file("text.txt");
while (getline(file, line)) {
istringstream is(line);
string word;
while (is >> word) {
++data[word];
}
}
cout << data["USER"] << endl;
return 0;
}
Let's try again. Once again, a vector isn't necessary. This is what I would consider to be the most C++ idiomatic way. It uses std::string's find() method to repeatedly find the substring in order until the end of the string is reached.
#include <fstream>
#include <iostream>
#include <string>
int main() {
// Read entire file into a single string.
std::ifstream file_stream("text.txt");
std::string file_contents(std::istreambuf_iterator<char>(file_stream),
std::istreambuf_iterator<char>());
unsigned count = 0;
std::string substr = "USER";
for (size_t i = file_contents.find(substr); i != std::string::npos;
i = str.find(substr, i + substr.length())) {
++count;
}
}
I'm reading a function from a file in the format f(x,y,f(x),g) once I read the input it is stored as a vector and I am trying to get each value between the commas so in this case i want to get x, y f(x) and g as separate chars/strings. I'm stuck, any ideas?
Here is the solution I came up with:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
//Split string into vector of strings
vector<string> split(string str, char delimiter)
{
vector<string> internal;
stringstream ss(str); // Turn the string into a stream.
string tok;
while(getline(ss, tok, delimiter))
{
internal.push_back(tok);
}
return internal;
}
int main()
{
string myInput = "f(x,y,f(x),g)";
//Extract the string between outer brackets
size_t startIndex = myInput.find_first_of("(") + 1;
size_t endIndex = myInput.find_last_of(")");
string innerStr = myInput.substr(startIndex, endIndex-startIndex);
//Split the result by comma
vector<string> sep = split(innerStr, ',');
for(unsigned int i = 0; i < sep.size(); ++i)
{
cout << sep[i] << endl;
}
}
Hope it helps
I know how to program in C# and VB but not have idea about how to use C++ and have to program a little exe to a barcode scanner that use C++ :(
In this moment I try to parse a scanned barcode that have multiple data sepparated with a "/", I find that exist a strtok function, tested it "manually" and worked ok but I not implemented yet a working function to call it correctly, what I have now:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int elemStr(char *str, char sep)
{
int cantElem;
unsigned ich;
cantElem = 0;
if (strlen(str) > 0) //at least 1 elem
cantElem++;
for (ich = 0; ich < strlen(str); ich++)
{
if (str[ich] == sep)
cantElem++;
}
return cantElem;
}
char* getElemStr(char *str, char sep[], int elem)
{
char *tempStr = NULL;
char *tok;
int currElem = 1;
// 1st data
strcpy( tempStr, str);
tok = strtok( tempStr, sep);
while( currElem != elem )
{
// Get next tokens:
tok = strtok( NULL, sep );
currElem++;
}
return tok;
}
void main( void )
{
char barcode[] = "710015733801Z/1/35";
char sep[] = "/";
char sep1 = sep[0];
char barcd[20];
char piezaChar[4];
int pieza;
char mtsChar[4];
int cantElem;
cantElem = elemStr(barcode, sep1 );
if (cantElem >= 1)
{
strcpy(barcd, getElemStr(barcode,sep,1) ); //pasa a str resultado;
printf("Cod: %s\n", barcd ); //STACK OVERFLOW HERE!
}
}
if I use strtok witout a function "getElemStr" it work ok but I try to use it on other places too.
Can I use strtok like this? You have a working example?
pd: I not have idea about pointers (sorry), good doc to learn about that?
Since you specifically asked about C++, I'm going to ignore your very c-style code and show you how to do this in C++:
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string barcode = "710015733801Z/1/35";
std::string sep = "/";
std::vector<std::string> v;
boost::split(v, barcode, boost::is_any_of(sep));
for(size_t i=0; i<v.size(); ++i)
std::cout << v[i] << '\n';
}
strtok destroys your original string. So i don't think it can be used with a char* that points to a static string. Static strings get copied to a read only portion of the executable.
Here is a C++ solution that doesn't use boost.
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string barcode = "710015733801Z/1/35";
std::stringstream ss(barcode);
std::string elem;
while(std::getline(ss, elem, '/'))
{
//do something else meaningful with elem
std::cout << elem << std::endl;
}
return 0;
}
Output:
710015733801Z
1
35