I'm trying to read characters (numbers) from a string, and then passing them as integers in a vector. Currently something like this:
int p;
std::string line = "1111222111"
std::vector<int> vec;
for(int i = 0; i < str.size(); i++)
{
if(line.find('0', static_cast<std::size_t>(i)) != line.npos)
p = 0;
else if(line.find('1', static_cast<std::size_t>(i)) != line.npos)
p = 1;
else if(line.find('2', static_cast<std::size_t>(i)) != line.npos)
p = 2;
vec.push_back(p);
}
When doing this, the vector ends only with 0's. Keep in mind that this is not the actual code, just a vague representation of the part where I have my problem. I think I must be doing something wrong in the line.find stuff, but I don't really know any other way to use it (not that I actually know how to really use it...). Thanks in advance guys!
You can make use of the isdigit function to determine if the character is a digit. If so, you can make use of the fact that ASCII orders the digits adjacent.
You can thus solve the problem with the following code:
for(int i = 0; i < str.size(); i++) {
int c = str[i]-'0';
if(c >= 0 && c <= 9) {
vec.push_back(c);
}
}
#include <vector>
#include <string>
int main(int argc, char *argv[])
{
std::vector<int> ans;
const std::string str = "1234";
for (int i = 0; i < str.size(); ++i) {
if ('0' <= str[i] && str[i] <= '9')
ans.push_back(str[i] - '0');
}
return 0;
}
I think you should instead of this :
for(int i = 0; i < str.size(); i++)
have this:
for(int i = 0; i < line.size(); i++)
str is not defined in your example. I think you meant line.
Related
I don't know how to use the find() function to check if a string contains a substring, then the program should print out all Words, and "Contains" if Sentence contains at least one of them. Can anyone help me out? My usage of find() sets A always to true. Thanks for help
#include <iostream>
#include <string>
using namespace std;
string Words, Sentence, buf;
int i, n, j = 0;
string arr[20];
bool A;
int main() {
cout << "Words separated by slashes";
cin >> Words;
cout << "Sentence";
cin >> Sentence;
for (i = 0; i <= Words.length(); i++)
{
if (Words[i] != '/')
{
buf = buf + Words[i];
}
else
{
arr[n] = buf;
n = n + 1;
buf = "";
}
}
for (j = 0; j <= n; j++)
{
cout << arr[j] << "\n";
if (Sentence.find(arr[j]) != string::npos)
{
A = true;
}
}
if (A == true)
{
cout << "Contains.";
}
else
{
enter code herecout << "Does not contain.";
}
}
There are a few bugs and issues in this code I think, but the biggest is the for loops all go too far by one.
for (i = 0; i <= Words.length(); i++)
and
for (j = 0; j <= n; j++)
should be
for (i = 0; i < Words.length(); i++)
and
for (j = 0; j < n; j++)
The valid indexes for a string, vector or array are zero upto but not including the size of the string, vector or array.
This mistake causes the bug that you see. Suppose you have two words in arr, e.g. arr = { "stack", "overflow", "", "", ... } . Because you go around the for loop one too many times you end up searching for arr[2] which equals "". This search always succeeds because every string contains the empty string. And so you always set A to true.
i was working on this question but there is some weird error in it. The problem is in the "Replace" function. I have commented the problem in the code below.
I made three dynamic character arrays (sentence, word1, word2) and used cin.getline to input. What i want to do is that if :
sentence = "I like pizza",
word1 = "like", and
word2 = "hate"
then I want sentence = "I hate pizza".
Also this is my first time using stack overflow so if there is any problem with this thread please let me know. Your help will be greatly appreciated.
void Replace(char* s, char* w1, char* w2)
{
int lisw = 0; //lisw = letters in single word
bool found = false;
for (int i = 0; s[i] != '\0' || found == true; i++)
{
lisw = 0;
//Problem is down here. The loop doesn't terminate when encountering a
//space character. When i used static_cast code to check the ASCII
//values only junk values were output. If i just cout<<s; then there is
//no problem but doing it here causes some weird logical errors.
for (int j = i; s[j] != ' '; j++)
{
lisw++;
cout << static_cast<int>(s[j]);
}
found = true;
for (int j = i; j < lisw; j++)
{
if (s[j] != w1[j])
{
found = false;
}
}
if (found == true)
{
for (int j = i; j < lisw; j++)
{
s[j] = w2[j];
}
}
i = i + lisw;
}
}
Ok so i found a solution thanks to the comments. I'll copy the corrected code below. The corrections can be seen in the comments.
void Replace(char* s,char* w1, char* w2)
{
int lisw = 0; //lisw = letters in single word
bool found =false;
for (int i=0;s[i]!='\0' && found!=true;i++) //Replaced || with &&.
{
lisw=0;
for (int j=i;s[j]!=' '&& s[j]!='\0';j++)//added: && s[j]!='\0' so the loop terminates because otherwise it kept finding "spaces" since the character array was of a larger size to accommodate any sentence.
{
lisw++;
}
found=true;
int k=0;
for (int j=i;j<lisw+i;j++) //loop goes until lisw+i instead of lisw
{
if (s[j]!=w1[k])
{
found=false;
}
k++;
}
k=0;
if (found==true)
{
for (int j=i;j<lisw+i;j++)//same as above.
{
s[j]=w2[k];
k++;
}
}
i=i+lisw;
}
}
So I got this weird thing that's happening to me.
I have a 2 dimensional char array, I'm suppose to put values in the array with the following conditions:
Each word (string) should be in a different array (different
line)
"." is an indicator that it is the end of the input.
This is my code:
const int MAX_STRS = 10, MAX_STR_LEN = 8;
int main()
{
char dict[MAX_STRS][MAX_STR_LEN] = { 0 };
getArray(dict);
return EXIT_SUCCESS;
}
void getArray(char array[][MAX_STR_LEN])
{
bool dot = false;
int i, j;
for ( i = 0; i < MAX_STRS && !dot; i++)
for ( j = 0; j < MAX_STR_LEN && !isspace(array[i][j - 1]); j++)
{
array[i][j] = cin.get();
if (array[i][j] == '.')
{
dot = true;
break;
}
}
}
The line I'm trying to read is:
blabla picked nice PeTer a hahaha of pickled Piper .
for some reason every time i=8, j automatically has the same value (j=8) and it skips this round of the loop.
Help would be much appreciated!
The problem was that when j=0, I asked him to check if array[-1] has whitespace.
Anyway here is the fixed code:
void getArray(char array[][MAX_STR_LEN])
{
bool dot = false;
int i, j;
for ( i = 0; i < MAX_STRS && !dot; i++)
for ( j = 0; j < MAX_STR_LEN ; j++)
{
array[i][j] = cin.get();
if (array[i][j] == '.')
{
dot = true;
break;
}
if( isspace(array[i][j]))
break;
}
}
Thank you Alan Stokes for bringing that to my attention!
I believe that your problem is with this:
for ( j = 0; j < MAX_STR_LEN && !isspace(array[i][j - 1]); j++)
Ask yourself what are you reading from when j is 0? That code tries to read from array[i][-1]. What is that? It could be anything!
If your loop is exiting early then that isspace check is probably returning true.
Sometimes to debug these things you need to discard all of your assumptions and check each thing individually using a debugger or print statements.
For example you could have put this line before your for loop:
cout << isspace(array[i][-1]);
I want to write a for loop that passes the strings for 0 till 9:
for (string j = "0"; j < "10"; j++) {
}
but it doesn't know the operator ++ (it gets an integer (1) and not a string "1").
I think to write: j+="1", but then j will be "01" and then "011"...
p.s. I don't want to use functions of #include <string> or something else. (stoi, etc)
any help appreciated!
Loop with integers, then manually convert it to a string?
Like
for (int i = 0; i < 10; i++)
{
string j(1, '0' + i); // Only works for single digit numbers
}
Do your iterations with integers, and convert them to strings inside the loop, like this:
// Your loop counter is of type int
for (int i = 0 ; i != 10 ; i++) {
// Use string stream to convert it to string
ostringstream oss;
oss << i;
// si is a string representation of i
string si = oss.str();
cout << si << endl;
}
This works for any kind of integers without limitations.
Here is a short demo.
Not that way, but...
char x[]={'0',0};
for(; x[0] <= '9'; ++x[0])
{
}
Edit: 0..99 version
char x[]={'0','0',0};
int stroffs = 1;
for(; x[0] <= '9'; ++x[0])
{
for(x[1] = '0'; x[1] <= '9'; ++x[1])
{
char * real_str = x + stroffs;
}
stroffs = 0;
}
You can do like j[0]++ to increase first char to next ascii value. but this is only for '0'-'9'
edit: Just an idea, not a perfect code: for 0 to 20;
i = 0;
(j > "9") && (i==0) ? j[i]++ : (++i, j="10");
With your constraints (although I have no idea how you use string without #include <string>):
const char* x[] =
{
"0", "1", .... , "10"
}
for ( int i = 0 ; i <= 10 ; i++ )
{
x[i]....
}
you can use atoi with:
#include <stdlib.h> // or #include <cstdlib>
for (int j = atd::atoi("0"); j < std::atoi("10"); j++) {
}
vector<string> grid();
for(int i = 0; i < 7; i++)
{
string hello(10, '.');
grid.push_back(hello);
}
vector<int> newVec(grid.size(), 0);
for(int i = 0; i < grid.size(); i++)
{
if(grid[0][i] = '.')
newVec[i] == 1;
}
You would expect that newVec would now have all of its elements equal to 1. But I keep getting all 0s. Any help?
At least two things are wrong:
You probably want if(grid[0][i] = '.') to be if(grid[0][i] == '.'). This is not the cause of the problem, though.
You want newVec[i] == 1; to be newVec[i] = 1;. That one is the source of why the elements in newVec are not having their values set to 1.