I am trying this code to perform the following function : given an input file and a word(string) output should be the lines in the file containing the given word along with the line number. But I am getting an error saying "no matching function for call to ..." in the line where I am performing string operation (strstr). Here is my code. Please help me solve this. I am facing the same error in other programs also where ever I perform operations involving strings.
#include<iostream>
#include<fstream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
int x;
char c;
ifstream iFile1, iFile2;
ofstream oFile;
char file1[50], file[50];
char word[50];
cout << "First file?\n";
gets(file1);
std::string str;
cout << "Word?\n";
gets(word);
iFile1.open(file1);
while (std::getline(iFile1, str)) {
x++;
if (strstr(str, word)) {
cout << "%d\t,x";
cout << str;
}
}
}
error: no matching function for call to 'strstr(std::string&,char[50])'
if(strstr(str,word))
^
char * strstr (char * str1, const char * str2 );
This is the signature of the strstr function, which requires both elements to be char*, but you are passing as first element a std::string&.
To fix this, try:
if (strstr(str.c_str(), word))
The c_str() method returns a char * to an array that contains the elements of the string
Also please note that the gets function is deprecated
Not the right answer, but still important to point out:
<string.h> is not <string>
<string.h>, and <cstring>, are header files defining several functions to manipulate C Strings and arrays (Source)
<string> defines std::string, which has the handy member function .c_str() allowing you to use functions which want a parameter of char*
Related
#include<iostream>
using namespace std;
int main() {
string str;
gets_s(str);
cout << str << endl;
return 0;
}
When I tried to run the above code it threw an error that no instance of gets_s() matched the argument list.
How can I pass an std::string instead of a char[] to gets_s() function if is possible?
The C function get_s takes a char* and a length argument, not a std::string.
Your best options are:
Formatted input:
std::cin >> str;
Read a line:
std::getline(std::cin, str);
Don't do that. Use the stream in a normal way:
#include<iostream>
using namespace std;
int main()
{
string str;
cin >> str;
cout << str << endl;
return 0;
}
gets_s has a significant limitation in that you must provide an upper limit on the number of characters you want to read.
Since you are using string the superior alternative is to use getline
#include <iostream>
#include <string>
using namespace std;
string str;
getline(cin, str);
This will expand the string to hold as many characters as are entered by the user.
gets_s() takes two arguments: pointer to char array and maximal size (your call is missing it). You cannot pass std::string - only C style strings.
Instead of C functions, why not use C++ way std::cin >> str or getline(std::cin, str)?
In C also don't use gets_s() (it's optional in C11) or gets() - use fgets() instead.
Well, there are a lot of answers about std::getline, but in case if you really need to use get_s, you may write such code:
size_t length = 10; // Just for example
std::string my_string(length, 0);
get_s(&my_string[0], length); // C++14 and older
get_s(my_string.data(), length); // C++17 and newer
How to print out the first element of a const string?
I tried to do std::cout << path[0] << std::endl; on CLion
but path[0] does not work and the IDE would warn.
CLion warns that
Cannot assign to return value because function 'operator[]' returns a const value.
type print(const std::string &path){}
You can use
std::string::at
It can be used to extract characters by characters from a given string.
Consider an example
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
string str = "goodday";
cout << str.at(0);
return 0;
}
Hope this will help you.
First of all you can ignore the warning sometimes the compiler complains about unnecessary things, secondly do not do the following:
type print(const std::string &path){}
Dangerous, first of all Passing a string as a reference?? Think about it from the compilers point of view, the string is const, each time you use the += you are actually create a new string. But if you use the & with the string you are telling the compiler that you are planning to modify the string object which has type const..... Use string path as a parameter but never, ever use string& path......
I meant to write program which will simply delete single letters from the input given by user, let's say we've got some text like: "monkey eat banana" and we supposed to delete the letter 'a' from the text above.
The final output supposed to look like this:
'monkey et bnn'
I've got the code which works pretty much flawlessly with single strings, but I have to use getline() function to obtain some longer texts, that is why I have to declare array of string, in order to pass it's size in the second argument of getline() function, like so:
string text[256];
getline(text, 256);
I would like to use getline() function without giving a size of an array, but I think it's impossible, therefore I need to stick with string array instead of a string.
The problem I've got is that I don't know how to correctly pass array of string, to use it as function's argument. Here's my code;
#include <iostream>
#include <string>
using namespace std;
void deleteLetter(string &text[], char c)
{
size_t positionL = text.find(c);
if(positionL == string::npos)
cout << "I'm sorry, there is no such letter in text" << endl;
else
text.erase(positionL, positionL);
cout << "After your character removed: " << text << endl;
}
int main()
{
string str1[256];
char a = 'a';
cin.getline(str1, 256);
deleteLetter(str1, a);
}
I know it's elementary stuff, but still I can't figure it out on my own.
Perhpahs I should reach out for your help.
It sounds to me like you don't need an array of strings. Just to read as many characters the user types, into a string. getline should deal fine with this.
int main()
{
std::string str1; // just a string here, not an array.
std::getline (std::cin,str1);
deleteLetter(str1, 'a');
}
Now you should change the signature of DeleteLetter to take a single string as argument.
void deleteLetter(std::string& text, char c);
How your are going to implement deleteLetter is another question. The way you have it, it will delete only the first occurence of 'a'.
To read a string from console input (cin), you can use the getline() function:
std::string line;
std::getline(std::cin, line);
To remove all the occurrences of a given letter from a string, you can use the so called erase-remove idiom, with a combination of the string::erase() method and the std::remove() algorithm.
(Note that this idiom is usually showed applied to std::vector, but don't forget that a std::string can also be viewed as a "container of characters" stored in sequence, similar to vector, so this idiom can be applied to string content as well.)
To pass a std::string to functions/methods, use the usual C++ rules, i.e.:
If the function is observing the string (without modifying it), pass using const reference: const std::string &
If the function does modify the content of the string, you can pass using non-const reference: std::string &
A simple compilable code follows:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
//
// NOTE:
// Since the content of 'text' string is changed by the
// removeLetter() function, pass using non-const reference (&).
//
void removeLetter(string& text, char letter)
{
// Use the erase-remove idiom
text.erase(remove(text.begin(), text.end(), letter),
text.end());
}
int main()
{
string line;
getline(cin, line);
cout << "Read string: " << line << endl;
removeLetter(line, 'a');
cout << "After removing: " << line << endl;
}
This is what I got with MSVC:
C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp
test.cpp
C:\Temp\CppTests>test.exe
monkey eats banana
Read string: monkey eats banana
After removing: monkey ets bnn
It's not very clear to me from your question if you also want to pass vectors of strings around (probably in other parts of your code)...
Anyway, if you want a vector of strings (i.e. you want to store some strings in a vector container) you can simply combine these STL class templates like this:
std::vector<std::string> strings;
To pass that to functions/methods, use the usual C++ rules, i.e.:
If the function is observing the array of strings (without modifying it), pass using const references (const &): vector<string> &
If the function does modify the content of the vector, you can pass using non-const references (&): vector<string> &
When I am using the following code to convert an string to a float, it is working fine. But the next code gives the error. Please tell me why is this happening? String is a char array only is what I read.
Code1 (working)
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char str[]="301.23";
float f=atof(str);
cout<<sizeof(str)<<" is size with contents "<<str<<endl;
cout<<sizeof(f)<<" is size with contents "<<f<<endl;
return 0;
}
Code 2(not working)
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
int main()
{
string str="301.23";
float f=atof(str);
cout<<sizeof(str)<<" is size with contents "<<str<<endl;
cout<<sizeof(f)<<" is size with contents "<<f<<endl;
return 0;
}
Error:
error: cannot convert std::string to const char* for argument 1 to double atof(const char*)
Please help
std::string is not a char array.
Use str.c_str() to get a const char* and you should be fine
Syntax:
#include <stdlib.h>
double atof( const char *str );
The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
The function stops reading the input string at the first character that it cannot recognize as part of a number. This character can be the null character that ends the string.
The atof() function expects a string in the following form:
Read syntax diagramSkip visual syntax diagram
>>-+------------+--+-----+--+-digits--+---+--+--------+-+------->
'-whitespace-' +- + -+ | '-.-' '-digits-' |
'- – -' '-.--digits-----------------'
Therefore your problem lies in the atof funcion which is not designed to accept string at it doesn't store characters in integer form.
Hope this helped.. :D
Try using #include<cstring> in place of #include <string>
Technically, You're only guaranteed std::string, but all popular implementations just pull in the C header and add a using statement...
is a C++ standard library include, and is C standard library include.
I'm trying to figure out how to print a string several times. I'm getting errors. I just tried the line:
cout<<"This is a string. "*2;
I expected the output: "This is a string. This is a string.", but I didn't get that. Is there anything wrong with this line? If not, here's the entire program:
#include <iostream>
using namespace std;
int main()
{
cout<<"This is a string. "*2;
cin.get();
return 0;
}
My compiler isn't open because I am doing virus scans, so I can't give the error message. But given the relative simplicity of this code for this website, I'm hoping someone will know if I am doing anything wrong by simply looking.
Thank you for your feedback.
If you switch to std::string, you can define this operation yourself:
std::string operator*(std::string const &s, size_t n)
{
std::string r; // empty string
r.reserve(n * s.size());
for (size_t i=0; i<n; i++)
r += s;
return r;
}
If you try
std::cout << (std::string("foo") * 3) << std::endl
you'll find it prints foofoofoo. (But "foo" * 3 is still not permitted.)
There is an operator+() defined for std::string, so that string + string gives stringstring, but there is no operator*().
You could do:
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string str = "This is a string. ";
cout << str+str;
cin.get();
return 0;
}
As the other answers pointed there's no multiplication operation defined for strings in C++ regardless of their 'flavor' (char arrays or std::string). So you're left with implementing it yourself.
One of the simplest solutions available is to use the std::fill_n algorithm:
#include <iostream> // for std::cout & std::endl
#include <sstream> // for std::stringstream
#include <algorithm> // for std::fill_n
#include <iterator> // for std::ostream_iterator
// if you just need to write it to std::cout
std::fill_n( std::ostream_iterator< const char* >( std::cout ), 2, "This is a string. " );
std::cout << std::endl;
// if you need the result as a std::string (directly)
// or a const char* (via std::string' c_str())
std::stringstream ss;
std::fill_n( std::ostream_iterator< const char* >( ss ), 2, "This is a string. " );
std::cout << ss.str();
std::cout << std::endl;
Indeed, your code is wrong.
C++ compilers treat a sequence of characters enclosed in " as a array of characters (which can be multibyte or singlebyte, depending on your compiler and configuration).
So, your code is the same as:
char str[19] = "This is a string. ";
cout<<str * 2;
Now, if you check the second line of the above snippet, you'll clearly spot something wrong. Is this code multiplying an array by two? should pop in your mind. What is the definition of multiplying an array by two? None good.
Furthermore, usually when dealing with arrays, C++ compilers treat the array variable as a pointer to the first address of the array. So:
char str[19] = "This is a string. ";
cout<<0xFF001234 * 2;
Which may or may not compile. If it does, you code will output a number which is the double of the address of your array in memory.
That's not to say you simply can't multiply a string. You can't multiply C++ strings, but you can, with OOP, create your own string that support multiplication. The reason you will need to do that yourself is that even std strings (std::string) doesn't have a definition for multiplication. After all, we could argue that a string multiplication could do different things than your expected behavior.
In fact, if need be, I'd write a member function that duplicated my string, which would have a more friendly name that would inform and reader of its purpose. Using non-standard ways to do a certain thing will ultimately lead to unreadable code.
Well, ideally, you would use a loop to do that in C++. Check for/while/do-while methods.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int count;
for (count = 0; count < 5; count++)
{
//repeating this 5 times
cout << "This is a string. ";
}
return 0;
}
Outputs:
This is a string. This is a string. This is a string. This is a string. This is a string.
Hey there, I'm not sure that that would compile. (I know that would not be valid in c# without a cast, and even then you still would not receive the desired output.)
Here would be a good example of what you are trying to accomplish. The OP is using a char instead of a string, but will essentially function the same with a string.
Give this a whirl:
Multiply char by integer (c++)
cout<<"This is a string. "*2;
you want to twice your output. Compiler is machine not a human. It understanding like expression and your expression is wrong and generate an error .
error: invalid operands of types
'const char [20]' and 'int' to binary
'operator*'