I have a string which has 1000 characters. I want to split this string to an array of strings of 5 characters each. The code is:
int main()
{
string myarray[200];
int k = 0;
string num = "a string with 1000 characters";
while(!num.empty())
{
strncpy(myarray[k],num.c_str(),5);
num.erase(0,5);
k++;
}
}
This code gives this error :
cannot convert 'std::string {aka std::basic_string}' to 'char*'
for argument '1' to 'char* strncpy(char*, const char*, size_t)'|
I tried the code without .c_str(), the result was same.
How can I fix this? Thanks.
Function strncpy expect first argument is char* while you passed string to it. Compiler will complain that it can't convert std::string to char*:
char *strncpy( char *dest, const char *src, std::size_t count );
Better use std::vector and call std::string::substr:
#include <string>
#include <vector>
std::string num("a string with 1000 characters");
std::vector<std::string> myarray;
myarray.reserve(200);
for (int i=0; i<num.size(); i+=5)
{
myarray.push_back(num.substr(i, 5));
}
You should use std::substr and std::vector:
#include <string>
#include <vector>
std::string num = "a string with 1000 characters";
std::vector<std::string> myArray;
for ( unsigned int i = 0; i < num.length(); i += 5 )
{
myArray.push_back( num.substr( i, 5 ) );
}
std::vector is a bit more flexible than array.
A working live example.
You may use std::substr as:
string MyArray[200];
for int i = 0;i<1000;i+=5)
{
MyArray[i] = num.substr(i,5);
}
And I would advice you to use vector<string> instead of MyArray[200] for a bit more flexibility.
Related
I'm currently solving problems for my high school final exam at programming in C++. I tried solving a problem in CodeBlocks, but it gives me this error at line 13:
error: invalid conversion from 'const char*' to 'int' [-fpermissive]
I don't see what is wrong.
The problem is about removing the last consonant from a string. The string is "mare frig saci" and it should produce "mare frig sai", removing the last 'c'.
Here is my code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[256];
int i;
cin.get(s,256);
for(i=strlen(s)-1;i=0;i--)
{
if(strchr(s,"aeiou")!=0)
strcpy(s+i+1,s+i-1);
}
cout<<s;
return 0;
}
There are a few problems:
i=0 is not a condition, it's an assignment. i>=0 is probably what you're looking for here
strchr take in a string and char (1), and return a pointer (2), not an int to be compared. Both (1) and (2) condition isn't sastified. In any case, strchr is not ideal to use here.
I recommended using std::string (as it's more easy to use and standard in C++) and std::string::find_last_of, which find the last character in string inside a set of characters, exactly what you wanted here:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s; getline(std::cin, s);
string cons = "bcdfghjklmnpqrstvwxyz";
size_t pos = s.find_last_of(cons);
if (pos != string::npos) //if a consonant is found
{
s.erase(pos, 1);
}
cout << s;
}
std::strchr - The valid signatures are
const char* strchr( const char* str, int ch );
char* strchr( char* str, int ch );
So, you are supplying it with the wrong things.
std::strcpy - "The behavior is undefined if the strings overlap" - so you can't use std::strcpy to move the end of the string to the new place. Instead use std::memmove.
Since the string you mention contains a space at the end, you must add space to the list of vowels.
You assign 0 to i instead of checking it's value.
Example:
#include <cstring>
#include <iostream>
int main() {
char s[256] = " mare frig saci ";
for (size_t len = strlen(s), i = len; i-- > 0;) { // corrected loop
if (std::strchr("aeiou ", s[i]) == nullptr) { // corrected check
std::memmove(s + i, s + i + 1, len - i); // corrected move
break; // and break out
}
}
std::cout << s << '\n';
}
cannot convert '__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> >, std::__cxx11::basic_string<char> >::value_type' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'gcc
sincerely i don't know why and how to correct this.
#include <stdio.h>
#include <conio.h>
#include <string>
#include <vector>
namespace anas
{
void passwordGenerator()
{
std::vector<std::string> PasswordString;
std::string ElencoAlfabeto("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
char CharAlfabeto[ElencoAlfabeto.length()];
for (int Lettere_Create = 0; Lettere_Create < 8; Lettere_Create++)
{
int NumeroCarattere = rand() % sizeof(CharAlfabeto);
CharAlfabeto [NumeroCarattere] = ElencoAlfabeto[NumeroCarattere];
PasswordString.push_back(CharAlfabeto[NumeroCarattere]);
}
for (int Lettere_Scritte = 0; Lettere_Scritte < 8; Lettere_Scritte++)
{
printf ( PasswordString.at(Lettere_Scritte) );
}
}
}
int main()
{
system("cls");
std ::printf("the program is started... \n \n");
anas::passwordGenerator();
}
the output should be a random 8 letter generator.
yes, this is my first time using vector ... here the article i use:
when i put the mouse-cursor on the at , i see 1 overload, what is mean overload?
In this line
printf ( PasswordString.at(Lettere_Scritte) );
The function printf needs a const char* but your are giving it a std::string.
In addition to the type mismatch, you should never ever pass arbitrary data as the first parameter of printf, because it will try to interpret format codes.
If you really want to use printf, this will work:
printf( "%s", PasswordString.at(Lettere_Scritte).c_str() );
You can skip the format code decoding entirely using puts:
puts( PasswordString.at(Lettere_Scritte).c_str() );
Or you can use C++ iostreams, which know about std::string and don't need the c_str() call at all:
std::cout << PasswordString.at(Lettere_Scritte);
I gotta question about Ice in C++. One of my methods requires that I pass in a Ice::ByteSeq. I would like to build this ByteSeq from a string. How is this conversion possible?
I tried the options below.
Ice::ByteSeq("bytes") // Invalid conversion to unsigned int
Ice::ByteSeq((byte*)"bytes") // Invalid conversion from byte* to unsigned int
(Ice::ByteSeq)"bytes" // Invalid conversion from const char& to unsigned int
(Ice::ByteSeq)(unsigned int)atoi("bytes") // Blank (obviously, why did I try this?)
How can I make this happen?
EDIT
"bytes" is a placeholder value. My actualy string is non-numeric text information.
Looking at the header, ByteSeq is an alias for vector<Byte>. You can initialise that from a std::string in the usual way
std::string s = "whatever";
Ice::ByteSeq bs(s.begin(), s.end());
or from a string literal with a bit more flappery, such as
template <size_t N>
Ice::ByteSeq byteseq_from_literal(char (&s)[N]) {
return Ice::ByteSeq(s, s+N-1); // assuming you don't want to include the terminator
}
Ice::ByteSeq bs = byteseq_from_literal("whatever");
You were almost there,
Ice::ByteSeq((unsigned int)atoi("bytes"));
should do it
Assuming your Ice::ByteSeq has a constructor that takes unsigned int
To split this down, it's basically doing
int num = atoi("12345"); // num = (int) 12345
unsigned int num2 = (unsigned int)num; // num2 = (unsigned int) 12345
Ice::ByteSeq(num2);
If Ice::ByteSeq is simply a vector of bytes you can convert a string to a vector of bytes by doing a variation of the following:
std::string str = "Hello World";
std::vector<char> bytes(str.begin(), str.end());
The implementation of Ice::Byte is an unsigned char just change the standard code I posted from:
std::vector<char> bytes(str.begin(), str.end());
to
std::vector<unsigned char> bytes(str.begin(), str.end());
and the generated vector should be directly compatible with an Ice::ByteSeq
sample code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::string str = "Hello World";
std::vector<unsigned char> bytes(str.begin(), str.end());
cout << str << endl;
for(int i=0; i < bytes.size(); i++)
std::cout << bytes[i] << '\n';
return 0;
}
Hope this helps:)
i am trying to put the words that there are in a txt file* into an array of strings.
But there is an error with the strcpy(). it sais: 'strcpy' : cannot convert parameter 1 from 'std::string' to 'char *' . Why is that? Isn't it possible to create an array of strings like this in c++?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void ArrayFillingStopWords(string *p);
int main()
{
string p[319];//lekseis sto stopwords
ArrayFillingStopWords(p);
for(int i=0; i<319; i++)
{
cout << p[i];
}
return 0;
}
void ArrayFillingStopWords(string *p)
{
char c;
int i=0;
string word="";
ifstream stopwords;
stopwords.open("stopWords.txt");
if( stopwords.is_open() )
{
while( stopwords.good() )
{
c = (char)stopwords.get();
if(isalpha(c))
{
word = word + c;
}
else
{
strcpy (p[i], word);//<---
word = "";
i++;
}
}
}
else
{
cout << "error opening file";
}
stopwords.close();
}
I suggest strcpy (p[i], word); be changed to p[i] = word;. This is the C++ way of doing things and takes advantage of the std::string assignment operator.
You don't need strcpy here. A simple assignment will do it: p[i] = word;. strcpy is for C-style strings, which are null-terminated arrays of characters:
const char text[] = "abcd";
char target[5];
strcpy(target, text);
Using std::string means you don't have to worry about getting the size of the array right, or about calling functions like strcpy.
How do I convert a string into an array of integers? Can I use sstream, because atoi doesn't work?!
As you said in the comments, you got a binary string and you want to convert it into integers. Use bitset for that:
std::istringstream is(str);
std::bitset<32> bits; // assuming each num is 32 bits long
while(is >> bits) {
unsigned long number = bits.to_ulong();
// now, do whatever you want with that long.
v.push_back(number);
}
If you only have one binary number in that string str, you can get away with
unsigned long number = std::bitset<32>(str).to_ulong();
Converting that in C is also possible...
long value;
char const *c = str;
for(;;) {
char * endp;
value = strtol(c, &endp, 2);
if(endp == c)
break;
/* huh, no vector in C. You gotta print it out maybe */
printf("%d\n", value);
c = endp;
}
atoi can't parse binary numbers. But strtol can parse them if you tell it the right base.
How exactly would you like the conversion to work?
Do you simply want an array containing the ASCII value of each character in the array? (so "abc" becomes [97, 98, 99, 0])?
Or do you want to parse the string somehow? ("1, 2, 3" becomes an array [1, 2, 3])
In the first case, in C++, I'd do something like this:
struct convert {
int operator()(char c) {
return static_cast<int>(c);
}
};
std::string str = "hello world";
std::vector<int> result;
std::transform(str.begin(), str.end(), std::back_inserter(result), convert())
Of course you could use a raw array instead of the vector, but since the length of the string is probably going to be variable, and then arrays are just asking for trouble.
If this wasn't what you wanted, you might want to edit your question to be more specific.
From what I understand, for input string "110013" would be converted to array {1,1,0,0,1,3}. Here is how to do it in C++:
string a = "1110011000";
vector<int> v;
for(int i = 0 ; i < a.length() ; i++){
v.push_back(a[i] -'0');
}
// Check the result
for(int i = 0 ; i < v.size() ; i++){
cout << v[i] << endl;
}
Quick string splitter routine:
convert(string str, string delim, vector<int>& results)
{
int next;
char buf[20];
while( (next= str.find_first_of(delim)) != str.npos ) {
if (next> 0)
results.push_back(atoi(str.substr(0,next), buf, 10));
str = str.substr(next+1);
}
if(str.length() > 0)
results.push_back(atoi(str.substr(0,next), buf, 10));
}
You can use stringstream instead of atoi (which does work, on a single int at a time)
int i;
stringstream s (input_string)
s >> i;
If you combine my and jalf's code, you'll get something really good.
Use the istream_iterator in conjunction with a string stream.
By Array I am assuming you really mean a std::vector as you don't know the number of integers at compile time. But the code can easily be modified to use an array rather than a vector.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::string data = "5 6 7 8 9";
std::vector<int> store;
std::stringstream dataStream(data);
std::copy(std::istream_iterator<int>(dataStream),
std::istream_iterator<int>(),
std::back_inserter(store)
);
// This line just copies the store to the std::cout
// To verify it worked.
std::copy(store.begin(),
store.end(),
std::ostream_iterator<int>(std::cout,",")
);
}
Language: C
Header:
#include <stdlib.h>
Function Prototype:
long int strtol(const char *nptr, char **endptr, int base);
Example Usage:
strtol(nptr, (char **) NULL, 10);