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
Related
I am a beginner and I just need a bit of help on why I getline is showing an error:
this is what I have so far
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
using namespace std;
const double TAX_RATE = 0.0825;
const int MAX_ITEMS = 1000;
const int MAX_TRANSACTIONS = 100;
int main(int argc, char const *argv[]){
string fname = "";
int itemCnt = 0, start = 0, end = 0;
int ids[MAX_ITEMS], qtys[MAX_ITEMS];
double costs[MAX_ITEMS], subtotals[MAX_TRANSACTIONS],
taxes[MAX_TRANSACTIONS], totals[MAX_TRANSACTIONS];
string names[MAX_ITEMS], paymentTypes[MAX_ITEMS], payments[MAX_ITEMS];
ifstream iFile;
if ( argc != 2 ) {
cout<<"usage: "<< argv[0]<< " <file name>" <<endl;
return 0;
} else {
iFile.open(argv[1]);
}
if (!iFile) {
cout<<"Error: Invalid file name"<<endl;
cin.clear();
}
while (!iFile.eof())
{
getline(iFile,str); //this isn't working
int commaLoc = str.find(',');
ids[itemCnt]= str.substr(0,commaLoc);
str = str.substr(commaLoc +1, str.length());
//string to int I'm not sure how to do I know its something with stoi() but not sure how to format it
}
return 0;
}
I am able to get the file to open but I'm not sure why getline isn't working it keeps saying something like
no instance of overload function
My csv file looks like:
1,Laptop,799.99,1,cash,1100
I need it to read the first number and because Its a string i don't know how to save it as an int
Multiple errors. First there is nothing called 'str' in your program. I will guess its just a string used as a temp buffer
do not do this (!File.eof) it doesnt do what you think.
while (iFile)
{
string str; <<<<<==== added
getline(iFile,str); //this isn't working <<<===is now
int commaLoc = str.find(',');
Next this line doesnt work because ids are ints and substring returns a string.
// ids[itemCnt]= str.substr(0,commaLoc);
ids[itemCnt]= stoi(str.substr(0,commaLoc)); <<<<==== fixed
str = str.substr(commaLoc +1, str.length());
}
I strongly recommend you use std::vector instead of c-style fixed size arrays. Takes 5 minutes to learn how to use them and they have huge benefits. If you must use fixed size arrays use std::array instead of c-style
You can read a string and try to convert it to a number in different ways. For example, since C++17, you can use from_chars. One of its overloads:
Receives a pair of begin and end char pointers, and an int variable,
tries to parse an int number, and
and returns the parsed number, together with a pointer to the first character that wasn't part of the match.
int i{};
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), i);
if (ec == std::errc{}) { /* do something with i */} else { /* error */ }
[Demo]
Full code (using a istrinstream instead of a ifstream):
#include <charconv> // from_chars
#include <iomanip>
#include <iostream>
#include <sstream> // istringstream
#include <system_error> // errc
constinit const int MAX_ITEMS = 10;
int main() {
std::istringstream iss{
"1,Laptop,799.99,1,cash,1100\n"
"2,PC,688.88,2,card,1101\n"
"blah,Keyboard,39.00,3,cash,1102"
};
size_t itemCnt{};
int ids[MAX_ITEMS]{};
std::string str{};
while (std::getline(iss, str)) {
// Parse counter
int i{};
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), i);
if (ec == std::errc{}) {
ids[itemCnt] = i;
// Remaining string
std::string remaining_string{ str.substr(ptr - str.data() + 1) };
std::cout << ids[itemCnt] << ", " << remaining_string << "\n";
}
else {
std::cout << "Error: invalid counter.\n";
}
++itemCnt;
}
}
// Outputs:
//
// 1, Laptop,799.99,1,cash,1100
// 2, PC,688.88,2,card,1101
// Error: invalid counter.
I'm a newbie in C++ learning the language and playing around. I wrote a piece of code which behavior I don't understand. Could someone explain why the code below prints out random junk and not the first character of the first string in the list (that is a).
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <stdio.h>
char* str2char(std::string str)
{
char cset[str.size()+1]; // +1 for the null character
for(int i = 0; i < str.size(); i++)
{
cset[i] = str[i];
}
cset[str.size()] = '\0';
return cset;
}
int main (int argc, char * const argv[]) {
std::vector< std::string > ladontakadet;
ladontakadet.push_back("aabcbbca");
ladontakadet.push_back("abcdabcd");
ladontakadet.push_back("cbbdcdaa");
ladontakadet.push_back("aadcbdca");
ladontakadet.push_back("cccbaaab");
ladontakadet.push_back("dabccbaa");
ladontakadet.push_back("ccbdcbad");
ladontakadet.push_back("bdcbccad");
ladontakadet.push_back("ddcadccb");
ladontakadet.push_back("baccddaa");
std::string v = ladontakadet.at(0);
char *r;
r = str2char(v);
std::cout << r[0] << std::endl;
return 0;
}
Why is my returning garbage, when I'm expecting it to output a?
Thnx for any help!
P.S. The output of this code is random. It doesn't always print the same character..:S
It's because you return a pointer to a local variable, a local variable that goes out of scope when the function returns.
You are already using std::string for the argument, use it instead of the array and the return pointer.
If your aim is to pass the content of a std::string to a function modifying the content of a char*:
#include <iostream>
#include <vector>
void f(char* s) {
s[0] = 'H';
}
std::vector<char> to_vector(const std::string& s) {
return std::vector<char>(s.c_str(), s.c_str() + s.size() + 1);
}
int main(void)
{
std::string s = "_ello";
std::vector<char> t = to_vector(s);
f(t.data());
std::cout << t.data() << std::endl;
}
Your function is returning garbage because you're returning the address of a local variable which goes out of scope after your function returns. It should probably look like this:
char* str2char(const std::string &str)
{
char *const cset = new char[str.size() + 1]; // +1 for the null character
strcpy(cset, str.c_str());
return cset;
}
You will need to delete your variable r by doing delete[] r;. Ideally though you wouldn't be using raw pointers, and you would use std::string for everything, or wrap the char * in a std::unique_ptr.
I want to split the strings on each line of my text file into an array, similar to the split() function in python. my desired syntax is a loop that enters every split-string into the next index of an array,
so for example if my string:
"ab,cd,ef,gh,ij"
, every time I encounter a comma then I would:
datafile >> arr1[i]
and my array would end up:
arr1 = [ab,cd,ef,gh,ij]
a mock code without reading a text file is provided below
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main(){
char str[] = "ab,cd,ef,gh,ij"; //" ex str in place of file contents/fstream sFile;"
const int NUM = 5;
string sArr[NUM];//empty array
char *token = strtok(str, ",");
for (int i=0; i < NUM; i++)
while((token!=NULL)){
("%s\n", token) >> sArr[i];
token = strtok(NULL, ",");
}
cout >> sArr;
return 0;
}
In C++ you can read a file line by line and directly get a std::string.
You will found below an example I made with a split() proposal as you requested, and a main() example of reading a file:
Example
data file:
ab,cd,ef,gh
ij,kl,mn
c++ code:
#include <fstream>
#include <iostream>
#include <vector>
std::vector<std::string> split(const std::string & s, char c);
int main()
{
std::string file_path("data.txt"); // I assumed you have that kind of file
std::ifstream in_s(file_path);
std::vector <std::vector<std::string>> content;
if(in_s)
{
std::string line;
std::vector <std::string> vec;
while(getline(in_s, line))
{
for(const std::string & str : split(line, ','))
vec.push_back(str);
content.push_back(vec);
vec.clear();
}
in_s.close();
}
else
std::cout << "Could not open: " + file_path << std::endl;
for(const std::vector<std::string> & str_vec : content)
{
for(unsigned int i = 0; i < str_vec.size(); ++i)
std::cout << str_vec[i] << ((i == str_vec.size()-1) ? ("") : (" : "));
std::cout << std::endl;
}
return 0;
}
std::vector<std::string> split(const std::string & s, char c)
{
std::vector<std::string> splitted;
std::string word;
for(char ch : s)
{
if((ch == c) && (!word.empty()))
{
splitted.push_back(word);
word.clear();
}
else
word += ch;
}
if(!word.empty())
splitted.push_back(word);
return splitted;
}
output:
ab : cd : ef : gh
ij : kl : mn
I hope it will help.
So, a few things to fix. Firstly, arrays and NUM are kind of limiting - you have to fix up NUM whenever you change the input string, so C++ provides std::vector which can resize itself to however many strings it finds. Secondly, you want to call strtok until it returns nullptr once, and you can do that with one loop. With both your for and NUM you call strtok too many times - even after it has returned nullptr. Next, to put the token into a std::string, you would assign using my_string = token; rather than ("%s\n", token) >> my_string - which is a broken mix of printf() formatting and C++ streaming notation. Lastly, to print the elements you've extracted, you can use another loop. All these changes are illustrated below.
char str[] = "ab,cd,ef,gh,ij";
std::vector<std::string> strings;
char* token = strtok(str, ",");
while ((token != nullptr))
{
strings.push_back(token);
token = strtok(NULL, ",");
}
for (const auto& s : strings)
cout >> s >> '\n';
Your code is overly complicated and wrong.
You probably want this:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main() {
char str[] = "ab,cd,ef,gh,ij"; //" ex str in place of file contents/fstream sFile;"
const int NUM = 5;
string sArr[NUM];//empty array
char *token = strtok(str, ",");
int max = 0;
while ((token != NULL)) {
sArr[max++] = token;
token = strtok(NULL, ",");
}
for (int i = 0; i < max; i++)
cout << sArr[i] << "\n";
return 0;
}
This code is still poor and no bound checking is done.
But anyway, you should rather do it the C++ way as suggested in the other answers.
Use boost::split
#include <boost/algorithm/string.hpp>
[...]
std::vector<std::string> strings;
std::string val("ab,cd,ef,gh,ij");
boost::split(strings, val, boost::is_any_of(","));
You could do something like this
std::string str = "ab,cd,ef,gh,ij";
std::vector<std::string> TokenList;
std::string::size_type lastPos = 0;
std::string::size_type pos = str.find_first_of(',', lastPos);
while(pos != std::string::npos)
{
std::string temp(str, lastPos, pos - lastPos);
TokenList.push_back(temp);
lastPos = pos + 1;
pos = str.find_first_of(',', lastPos);
}
if(lastPos != str.size())
{
std::string temp(str, lastPos, str.size());
TokenList.push_back(temp);
}
for(int i = 0; i < TokenList.size(); i++)
std::cout << TokenList.at(i) << std::endl;
I was trying to improve my reply to another question here How to cut the content of a string till a particular string or position? to use pointer arithmetic and std::substr so I ended up with the following
#include <iostream>
#include <string>
#include <cstring>
std::string getString(std::string fullString){
char string[80];
char* endString;
strcpy(string, fullString.c_str());
strtok(string, "|");
for(int i = 0; i < 4; i++){
endString = strtok(NULL, "|");
}
return fullString.substr(endString - string, std::string::npos);
}
int main( void ){
std::string str("{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread|./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....");
std::cout << getString(str) << std::endl;
return 0;
}
However that crashes with a segmentation fault error, if I change it to
#include <iostream>
#include <string>
#include <cstring>
std::string getString(std::string fullString){
char string[80];
char* endString;
strcpy(string, fullString.c_str());
strtok(string, "|");
for(int i = 0; i < 4; i++){
endString = strtok(NULL, "|");
}
std::cout << fullString.substr(endString - string, std::string::npos) << std::endl;
return fullString.substr(endString - string, std::string::npos);
}
int main( void ){
std::string str("{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread|./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....");
std::cout << getString(str) << std::endl;
return 0;
}
The program runs fine and the output is as expected
./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....
./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....
why does it crash on the first scenario?
Your input string is 120 bytes wide. Your C-string buffer is 80 bytes wide. Hrmm.
Use the find functions instead of this error-prone C nonsense!!
To get everything since the last |:
#include <iostream>
#include <string>
#include <stdexcept>
std::string getString(const std::string& fullString)
{
size_t pos = fullString.rfind('|');
if (pos == std::string::npos)
throw std::runtime_error("Could not find a '|'!");
return fullString.substr(pos+1);
}
int main()
{
std::string str("{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread|./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....");
std::cout << getString(str) << std::endl;
}
(live demo)
Adjust as needed to scan back for the 2nd, 3rd, 4th |.
Your program has undefined behaviour because the length of the string stored in str is greater than 80 characters. Thus in this statement
strcpy(string, fullString.c_str());
you overwrite memory beyond array string.
Moverover it is a bad approach to use C function strtok instead of member function find (or rfind) of class std::string.
Also it is not clear why exactly magic number 4 is used in the loop
for(int i = 0; i < 4; i++){
endString = strtok(NULL, "|");
}
I have to split a sample string using strok function using C++.
The sample string is: "This|is||a||sample||string|", while split this using strok normally.
#include <stdio.h>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string str="This||a||sample||string|";
string a;
str=strtok ((char *)str.c_str(),"|");
while (str.c_str() != NULL)
{
printf ("str:%s\n",str.c_str());
str = strtok (NULL, "|");
}
return 0;
}
Result:
str:This
str:a
str:sample
str:string
While changing the same string into "This| |a| |sample| |string|" gives the expected result:
str:This
str:
str:a
str:
str:sample
str:
str:string
How can I get the expect result without changing the string?
Using std::strtok on std::string will yield undefined behaviour, since std::strtok is destructive (hint: std::string::c_str() returns const char*).
Instead, use std::string::find and std::string::substr multiple times:
#include <iostream>
#include <string>
#include <iterator>
template <class OutputIt>
OutputIt safe_tokenizer(const std::string & s, char token, OutputIt out){
std::string::size_type pos = 0, f;
while((f = s.find(token, pos)) != std::string::npos){
*out++ = s.substr(pos, f - pos);
pos = f + 1;
}
if(pos < s.size())
*out++ = s.substr(pos);
return out;
}
int main(){
const std::string str = "Hello|World|How|Are|You";
safe_tokenizer(str, '|', std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
printf? strtok? You still coding in C. And C library is not really a good way (most times) to do things in C++.
In C++ we tend to avoid operating with naked pointers, C arrays and C strings, but use STL or Boost facilities.
Check this thread for a complete examples "in real C++"
Edit: here is another thread, even better.
Edit2: And if you look at right side of this page, you can find column "Related", with many useful links on your topic =)
try at strtok function
char * TOKEN;
char * mystrtok( char * string,
const char * control)
{
char * str=NULL;
if(string == NULL)
{
str = TOKEN;
if(*str == 0)
return NULL;
}
else
str = string;
string = str;
for ( ; *str ; str++ )
{
if(*str == *control)
{
*str++ = '\0';
break;
}
}
TOKEN = str;
return string;
}