I am having so much trouble trying to solve this one out. I have to read a .c file that has three functions (add, sub and main) and I want to print to the console the name of their variables with the name of the function in brackets. I tried implementing a string function_name in my struct to store the value of the functions, but I don't know how to print it next to my variables until I hit another function. Any help or advice will be much appreciated.
For example:
From this .c text
int add ( int a , int b )
{
return a + b ;
}
I want to get this:
add, line 1, function, int, referenced 2
a (add), line 1, variable, int, referenced 1
b (add), line 1, variable, int, referenced 1
But I get this:
add(add), line 1, function, int, referenced 16
a, line 1, variable, int, referenced 15
b, line 1, variable, int, referenced 15
My code so far looks like this.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct identifier
{
string id_name;
string function_name;
int id_count;
string id_function;
string id_type;
int id_ref;
};
int main(int argc, char** argv)
{
if (argc < 2)
{
cout << "ERROR: There is no file selected." << endl;
}
ifstream file(argv[1]);
string line;
string token;
vector<identifier> id_list;
int line_counter = 0;
int num_functions = 0;
int num_variables = 0;
int num_if = 0;
int num_for = 0;
int num_while = 0;
while (getline(file, line))
{
stringstream stream(line);
line_counter++;
while (stream >> token)
{
bool found = false;
for (auto& v : id_list)
{
if (v.id_name == token)
{
//We have seen the word so add one to its count
v.id_ref++;
found = true;
break;
}
}
if (token == "int" || token == "int*")
{
string star = token;
identifier intI;
stream >> token;
string name = token;
intI.id_name = name;
intI.id_count = line_counter;
intI.id_type = "int";
stream >> token; //Get the next token
if (token == "(")
{
//We have a function
intI.id_function = "function";
if (intI.id_name != "main")
{
intI.function_name = "(" + name + ")";
}
num_functions++;
}
else
{
//We have a variable
intI.id_function = "variable";
if (star == "int*")
{
intI.id_type = "int*";
}
num_variables++;
}
id_list.push_back(intI);
}
}
file.close();
//Print the words and their counts
for (auto& v : id_list)
{
cout << v.id_name << v.function_name << ", line " << v.id_count << ", " << v.id_function << ", " << v.id_type << ", referenced " << v.id_ref << endl;
}
return 0;
I can see you're incrementing id_ref now, but it's still not initialized, so you have undefined behaviour. Easiest way is to do = 0; where its defined in the struct.
As for your function, assuming there's no nested functions here, then you can just use a variable to keep track of that.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
struct identifier {
std::string id_name;
std::string function_name;
int id_count;
std::string id_function;
std::string id_type;
int id_ref = 0; // if not initialized, then you will get seemingly random numbers
};
int main( int argc, char **argv ) {
if ( argc < 2 ) {
std::cout << "ERROR: There is no file selected." << std::endl;
return 1; // quit early
}
std::ifstream file( argv[1] );
std::string line;
std::string token;
std::vector<identifier> id_list;
int line_counter = 0;
int num_functions = 0;
int num_variables = 0;
int num_if = 0;
int num_for = 0;
int num_while = 0;
std::string current_function; // keep track of the function
while ( std::getline( file, line ) ) {
std::stringstream stream( line );
line_counter++;
while ( stream >> token ) {
bool found = false;
for ( auto &v : id_list ) {
if ( v.id_name == token ) {
//We have seen the word so add one to its count
v.id_ref++;
found = true;
break;
}
}
if ( token == "int" || token == "int*" ) {
std::string star = token;
identifier intI;
stream >> token;
std::string name = token;
intI.id_name = name;
intI.id_count = line_counter;
intI.id_type = "int";
stream >> token; //Get the next token
if ( token == "(" ) {
//We have a function
intI.id_function = "function";
if ( intI.id_name != "main" ) {
current_function = name; // update the current function name
}
num_functions++;
} else {
intI.function_name = "(" + current_function + ")"; // add the function name to the variable name
//We have a variable
intI.id_function = "variable";
if ( star == "int*" ) {
intI.id_type = "int*";
}
num_variables++;
}
id_list.push_back( intI );
}
}
}
//file.close();
//Print the words and their counts
for ( const auto &v : id_list ) {
std::cout << v.id_name << v.function_name << ", line " << v.id_count << ", " << v.id_function << ", " << v.id_type << ", referenced " << v.id_ref << std::endl;
}
return 0;
}
Also, some recommended reading on using namespace std
Working example modified to work with a string, instead of parameter: https://godbolt.org/z/jKqqrhce6
Related
I've got a large text document that including adjacent numbers and letters.
Just like that,
JACK1940383DAVID30284HAROLD68372TROY4392 etc.
How can i split this like below in C++
List: Jack / 1940383 , David/30284, ...
You can use std::string::find_first_of() and std::string::find_first_not_of() in a loop, using std::string::substr() to extract each piece, eg:
std::string s = "JACK1940383DAVID30284HAROLD68372TROY4392";
std::string::size_type start = 0, end;
while ((end = s.find_first_of("0123456789", start)) != std::string::npos) {
std::string name = s.substr(start, end-start);
start = end;
int number;
if ((end = s.find_first_not_of("0123456789", start)) != std::string::npos) {
number = std::stoi(s.substr(start, end-start));
}
else {
number = std::stoi(s.substr(start));
}
start = end;
// use name and number as needed...
}
Online Demo
You can use regex like this:
#include <iostream>
#include <string>
#include <regex>
#include <vector>
// create a struct to group your data
// this makes it easy to store it in a vector.
struct person_t
{
std::string name;
std::string number;
};
// overloaded output operator for printing one person's details
std::ostream& operator<<(std::ostream& os, const person_t& person)
{
std::cout << person.name << ": " << person.number << std::endl;
return os;
}
// get a vector of person_t based on the input
auto get_persons(const std::string& input)
{
// make a regex in this case a regex that will match one or more capital letters
// and groups them using the ()
// then match one or more digits and group them too.
static const std::regex rx{ "([A-Z]+)([0-9]+)" };
std::smatch match;
// a vector to hold all the persons
std::vector<person_t> persons;
// start at begin of string and look for first part of the string
// that matches the regex.
auto cbegin = input.cbegin();
while (std::regex_search(cbegin, input.cend(), match, rx))
{
// match[0] will contain the whole match,
// match[1]-match[n] will contain the groups from the regular expressions
// match[1] will contain the match with characters and thus the name
// match[2] will contain the match with the numbers and thus the number.
// create a person_t struct with this info
person_t person{ match[1], match[2] };
// and add it to the vector
persons.push_back(person);
cbegin = match.suffix().first;
}
return persons;
}
int main()
{
// parse and split the string
auto persons = get_persons("JACK1940383DAVID30284HAROLD68372TROY4392");
// show the output
for (const auto& person : persons)
{
std::cout << person;
}
}
As pointed in other good answers you can use
find_first_of(), find_first_not_of() and substr() from std::string in a loop
regex
But it may be too much. I will add 3 more examples that you may find
simpler.
The first 2 programs expects the file name on the command line for (my) convenience here, and the test file is in.txt. Contents are the same as posted
JACK1940383DAVID30284HAROLD68372TROY4392
The last example just parses the string data declared as a char[]
1. Using fscanf()
Since the target is to consume formatted data, fscanf() is an option. As the data structure is very simple, the program is just a one line loop:
char mask[] = "%50[^0-9]%50[0-9]";
while ( 2 == fscanf(F, mask, tk_key, tk_value))
std::cout << tk_key << "/" << tk_value << "\n";
program output
output is the same for all examples
JACK/1940383
DAVID/30284
HAROLD/68372
TROY/4392
code for ex. 1
#include <errno.h>
#include <iostream>
int main(int argc,char** argv)
{
if (argc < 2)
{ std::cerr << "Use: pgm FileName\n";
return -1;
}
FILE* F = fopen(argv[1], "r");
if (F == NULL)
{
perror("Could not open file");
return -1;
}
std::cerr << "File: \"" << argv[1] << "\"\n";
char tk_key[50], tk_value[50];
char mask[] = "%50[^0-9]%50[0-9]";
while ( 2 == fscanf(F, mask, tk_key, tk_value))
std::cout << tk_key << "/" << tk_value << "\n";
fclose(F);
return 0;
}
using a state machine
There are just 2 states so it is not a fancy FSA ;) State machines are good for representing this kind of stuff, albeit here this seems to be overkill.
#define S_LETTER 0
#define S_DIGIT 1
#include <algorithm>
#include <iostream>
#include <fstream>
using iich = std::istream_iterator<char>;
int main(int argc,char** argv)
{
std::ifstream in_file{argv[1]};
if ( not in_file.good()) return -1;
iich p {in_file}, eofile{};
std::string token{}; // string to build values
char st = S_LETTER; // state value for FSA
std::for_each(p, eofile,
[&token,&st](char ch)
{
char temp = 0;
switch (st)
{
case S_LETTER:
if ((ch >= '0') && (ch <= '9'))
{
std::cout << token << "/";
token = ch;
st = S_DIGIT; // now in number
}
else token += ch; // concat in string
break;
case S_DIGIT:
default:
if ((ch < '0') || (ch > '9'))
{ // is a letter
std::cout << token << "\n";
token = ch;
st = S_LETTER; // now in name
}
else token += ch; // concat in string
break;
}; // switch()
});
std::cout << token << "\n"; // print last token
}
Here we have no loop. for_each gets the data from an iterator and passes it to a function that builds the name and the value as strings and couts them
Output is the same
3. a simple FSA to consume the data
#define S_LETTER 0
#define S_DIGIT 1
#include <iostream>
int main(void)
{
char one[] = "JACK1940383DAVID30284HAROLD68372TROY4392";
char* p = (char*)&one;
char* token = p;
char st = S_LETTER;
char temp = 0;
while (*p != 0)
{
switch (st)
{
case S_LETTER:
if ((*p >= '0') && (*p <= '9'))
{
temp = *p;
*p = 0;
std::cout << token << "/";
*p = temp;
token = p;
st = S_DIGIT; // now in number
}
break;
case S_DIGIT:
default:
if ( (*p < '0') || (*p > '9'))
{ // letter
temp = *p;
*p = 0;
std::cout << token << "\n";
*p = temp;
token = p;
st = S_LETTER; // now in name
}
break;
}; // switch()
p += 1; // next symbol
}; // while()
std::cout << token << "\n"; // print last token
}
This code just uses a C-style loop to parse the input data
Basically, I have to show each word with their count but repeated words show up again in my program.
How do I remove them by using loops or should I use 2d arrays to store both the word and count?
#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <cstring>
#include <conio.h>
#include <time.h>
using namespace std;
char* getstring();
void xyz(char*);
void tokenizing(char*);
int main()
{
char* pa = getstring();
xyz(pa);
tokenizing(pa);
_getch();
}
char* getstring()
{
static char pa[100];
cout << "Enter a paragraph: " << endl;
cin.getline(pa, 1000, '#');
return pa;
}
void xyz(char* pa)
{
cout << pa << endl;
}
void tokenizing(char* pa)
{
char sepa[] = " ,.\n\t";
char* token;
char* nexttoken;
int size = strlen(pa);
token = strtok_s(pa, sepa, &nexttoken);
while (token != NULL) {
int wordcount = 0;
if (token != NULL) {
int sizex = strlen(token);
//char** fin;
int j;
for (int i = 0; i <= size; i++) {
for (j = 0; j < sizex; j++) {
if (pa[i + j] != token[j]) {
break;
}
}
if (j == sizex) {
wordcount++;
}
}
//for (int w = 0; w < size; w++)
//fin[w] = token;
//cout << fin[w];
cout << token;
cout << " " << wordcount << "\n";
}
token = strtok_s(NULL, sepa, &nexttoken);
}
}
This is the output I get:
I want to show, for example, the word "i" once with its count of 5, and then not show it again.
First of all, since you are using c++, I would recommend you to split text in c++ way(some examples are here), and store every word in map or unordered_map. Example of my realization you can find here
But if you don't want to rewrite your code, you can simply add a variable that will indicate whether a copy of the word was found before or after the word position. If a copy was not found in front, then print your word
This post gives an example to save each word from your 'strtok' function into a vector of string. Then, use string.compare to have each word compared with word[0]. Those indexes match with word[0] are marked in an int array 'used'. The count of match equals to the number marks in the array used ('nused'). Those words of marked are then removed from the vector, and the remaining carries on to the next comparing process. The program ends when no word remained.
You may write a word comparing function to replace 'str.compare(str2)', if you prefer not to use std::vector and std::string.
#include <iostream>
#include <string>
#include <vector>
#include<iomanip>
#include<cstring>
using namespace std;
char* getstring();
void xyz(char*);
void tokenizing(char*);
int main()
{
char* pa = getstring();
xyz(pa);
tokenizing(pa);
}
char* getstring()
{
static char pa[100] = "this is a test and is a test and is test.";
return pa;
}
void xyz(char* pa)
{
cout << pa << endl;
}
void tokenizing(char* pa)
{
char sepa[] = " ,.\n\t";
char* token;
char* nexttoken;
std::vector<std::string> word;
int used[64];
std::string tok;
int nword = 0, nsize, nused;
int size = strlen(pa);
token = strtok_s(pa, sepa, &nexttoken);
while (token)
{
word.push_back(token);
++nword;
token = strtok_s(NULL, sepa, &nexttoken);
}
for (int i = 0; i<nword; i++) std::cout << word[i] << std::endl;
std::cout << "total " << nword << " words.\n" << std::endl;
nsize = nword;
while (nsize > 0)
{
nused = 0;
tok = word[0] ;
used[nused++] = 0;
for (int i=1; i<nsize; i++)
{
if ( tok.compare(word[i]) == 0 )
{
used[nused++] = i; }
}
std::cout << tok << " : " << nused << std::endl;
for (int i=nused-1; i>=0; --i)
{
for (int j=used[i]; j<(nsize+i-nused); j++) word[j] = word[j+1];
}
nsize -= nused;
}
}
Notice that the removal of used words has to do in backward order. If you do it in sequential order, the marked indexes in the 'used' array will need to be changed. A running test:
$ ./a.out
this is a test and is a test and is test.
this
is
a
test
and
is
a
test
and
is
test
total 11 words.
this : 1
is : 3
a : 2
test : 3
and : 2
I read your last comment.
But I am very sorry, I do not know C. So, I will answer in C++.
But anyway, I will answer with the C++ standard approach. That is usually only 10 lines of code . . .
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <regex>
// Regex Helpers
// Regex to find a word
static const std::regex reWord{ R"(\w+)" };
// Result of search for one word in the string
static std::smatch smWord;
int main() {
std::cout << "\nPlease enter text: \n";
if (std::string line; std::getline(std::cin, line)) {
// Words and its appearance count
std::map<std::string, int> words{};
// Count the words
for (std::string s{ line }; std::regex_search(s, smWord, reWord); s = smWord.suffix())
words[smWord[0]]++;
// Show result
for (const auto& [word, count] : words) std::cout << word << "\t\t--> " << count << '\n';
}
return 0;
}
I'm struggling to find a way to decrease the value in a string every time the string is shown.
Using the code below, consider that the 1st line of the text file is some text #N. #N should be replaced by a number decreasing from 18 to 1. When it reaches 0 it should go back to 18.
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void find_and_replace(string & source, string const & find, string const & replace)
{
for (string::size_type i = 0; (i = source.find(find, i)) != string::npos;) {
source.replace(i, find.length(), replace);
i += replace.length();
}
}
int main(int argc, char * argv[])
{
std::ifstream fileIn("Answers.txt", std::ios::in | std::ios::binary);
string question;
string line;
if (!fileIn) {
cout << "Cannot open input file!" << endl;
return 1;
}
while (getline(fileIn, line)) {
if (line == "The answer can be found in a secret place in the woods.") {
fileIn.clear();
fileIn.seekg(0, ios::beg);
}
cout << "Ask a question followed by the Enter key. Or type 'exit' to Exit program.\n";
getline(cin, question);
system("CLS");
find_and_replace(line, "#N", "18");
if (question == "") {
cout << "Your input cannot be blank. Please try again.\n\n";
}
else if (question == "exit")
exit(0);
else {
cout << "Q: " + question
<< "\nA: " + line + "\n\n";
}
}
}
This code only changes #N to 18, nothing more.
Please help guys.
You have hardcoded the value to 18, and you don't have any code which decrements the number.
Try these changes
put this at the start of main
int tempVar=18;
char buffer[100];
and replace
find_and_replace(line, "#N", "18");
with
sprintf(buffer,"%d",tempVar--)
if(tempVar<0)
tempVar=18;
find_and_replace(line, "#N", buffer);
https://www.programiz.com/cpp-programming/library-function/cstdio/sprintf
You can use something like:
#include <sstream>
#include <string>
class Replacer
{
const std::string token_;
const int start_;
int current_;
public:
explicit Replacer(const std::string & token, int start)
: token_(token), start_(start), current_(start)
{
}
std::string replace(const std::string & str)
{
const std::size_t pos = str.find(token_);
if (pos == std::string::npos)
return str;
std::string ret(str);
std::ostringstream oss;
oss << current_;
ret.replace(pos, token_.size(), oss.str());
--current_;
if (current_ == 0)
current_ = start_;
return ret;
}
};
And then you can use it like:
std::string examples[] = {
"",
"nothing",
"some number #N",
"nothing",
"some other #N number",
"nothing",
"#N another test",
"nothing",
};
Replacer replacer("#N", 18);
for (int i = 0; i < 8; ++i)
std::cout << replacer.replace(examples[i]) << '\n';
This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 8 years ago.
I tried to convert int into a string , but it doesn't work I dont know why...
here my Code:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <array>
using namespace std;
int main()
{
struct Studentendaten {
int matrnr;
string name;
string vorname;
string datum;
float note;
};
Studentendaten stud;
array<Studentendaten,100> studArray ;
FILE * pFile;
int ch;
int mnr;
string sub;
string sub1;
string sub2;
string sub3;
string sub4;
string sub5;
int i = 0;
int pos ;
pFile=fopen("studentendaten.txt","r");
if (pFile==nullptr)
{
perror ("Fehler beim öffnen der Datei");
}
else
{
while (ch != EOF)
{
ch = fgetc(pFile);
sub += (char)(ch);
pos = sub.find(";");
if (pos != -1)
{
sub1 = sub.substr(0,pos);
sub2 = sub.substr(pos+1,pos);
sub3 = sub.substr(pos+1,pos);
sub4 =sub.substr(pos+1,pos);
sub5 =sub.substr(pos+1,pos);
mnr =stoi(sub1);
stud.matrnr = mnr;
stud.name = sub2;
stud.vorname = sub3;
stud.datum = sub4
stud.note = float(sub5);
}
if (ch == '\n')
{
stud = {matrn,name,vorname,datum,note};
studArray.[i] = stud;
i++;
}
putchar(ch);
}
fclose (pFile);
}
return 0;
}
I tried int mnr =stoi(sub1);
as well as int mnr = atoi(sub1);
where sub1 = "029383214" something like that.... why does it not work? Compiler complains...
Simply use a std::stringstream:
int parse_int( const std::string& str )
{
std::stringstream ss( str );
int value;
if( ss >> value )
return value;
else
throw;
}
You can use stringstream:
#include <sstream>
...
// int to string
int intVar = 10;
std::stringstream out;
out << intVar;
std::string converted = out.str();
// string to int
std::string src = "555";
std::stringstream in(str);
int result = 0;
in >> result;
And check boost::lexical_cast as well.
Use std::to_string(int).
Reference.
You can use std::to_string for simple cases or std::stringstream when you need more control over formatting (zero padding, hexadecimal etc.)
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main(int argc, const char * argv[]) {
int value = 19;
cout << to_string( value ) << endl;
stringstream s1, s2;
s1 << setfill('0') << setw(4) << value;
s2 << "0x" << hex << setfill('0') << setw( 8 ) << value;
cout << s1.str() << endl << s2.str() << endl;
}
I would rather use boost::lexical_cast if I were on your place
string stringValue = lexical_cast<string>(101);
int intValue = lexical_cast<int>("101");
http://www.boost.org/doc/libs/1_54_0/doc/html/boost_lexical_cast.html
I have a little problem with a few simple lines of code.
Following lines I used to call my method:
char** paras = new char*;
inputLength = charUtils::readParameterFromConsole(paras, paraCount, stringBeginningIndex);
The method looks like following:
int charUtils::readParameterFromConsole(char** &inputs, int ¶Count, int &stringBeginningIndex) {
char input[BUFFER_STRING_LENGTH];
cin.getline(input, BUFFER_STRING_LENGTH);
if(strlen(input) > 0)
{
bool stringBeginning = false;
char* part = "";
string partString = "";
for(int i = 0; i < paraCount; i++)
{
if (i == 0)
part = strtok(input, " ");
else
part = strtok(NULL, " ");
inputs[i] = part;
}
} else
{
cout << "Error! No Input!" << endl;
}
cout << &inputs[0] << endl;
cout << inputs[0] << endl;
return strlen(input);
}
In the method readParameterFromConsole are the values correct, but in the calling method they aren't correcy any longer.
I am facing that problem since I refactored the code and make an new class.
Can anyone give me an advice please?
You are passing back pointers into a stack allocated variable, input when you say inputs[i] = part, because part is a pointer into input handed back by strtok.
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Your code as I'm writing this:
int charUtils::readParameterFromConsole(char** &inputs, int ¶Count, int &stringBeginningIndex) {
char input[BUFFER_STRING_LENGTH];
cin.getline(input, BUFFER_STRING_LENGTH);
if(strlen(input) > 0)
{
bool stringBeginning = false;
char* part = "";
string partString = "";
for(int i = 0; i < paraCount; i++)
{
if (i == 0)
part = strtok(input, " ");
else
part = strtok(NULL, " ");
inputs[i] = part;
}
} else
{
cout << "Error! No Input!" << endl;
}
cout << &inputs[0] << endl;
cout << inputs[0] << endl;
return strlen(input);
}
A main problem is that you're setting inputs[i] = pointer into local array. That array doesn't exist anymore when the function returns. Undefined behavior if you use any of those pointers.
As I understand it you want an array of "words" as a result.
That's easy to arrange (note: code untouched by compiler's hands):
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
bool throwX( char const s[] ) { throw std::runtime_error( s ); }
typedef std::vector<std::string> StringVector;
std::string lineFromUser()
{
std::string line;
std::getline( cin, line )
|| throwX( "lineFromUser failed: std::getline failed" );
return line;
}
void getWordsOf( std::string const& s, StringVector& result )
{
std::istringstream stream( s );
std::string word;
StringVector v;
while( stream >> word )
{
v.push_back( word );
}
result.swap( v );
}
StringVector wordsOf( std::string const& s )
{
StringVector result;
getWordsOf( s, result );
return result;
}
// Some call, like
StringVector const words = wordsOf( lineFromUser() );
Again, this is off the cuff code, please just correct any syntax erors.
Cheers & hth.,