Checking for spaces in C++? - c++

I'm writing an encryption program for class. I need to be able to track the position of spaces in a string, as well as adding 13 to the ASCII value of each character of the string. I keep getting an error in line 46, and I don't see what I'm doing wrong.
/*
program 4
use an array to store the string
convert decimal values to ASCII, add 13 to the ASCII values,
convert back to decimal
the character for the space shoud be determined by the character
that came before it.
The character before it should have 4 added to it and
placed after itself to act as the space.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int valueChange(string array), length(string array);
int spacePosition[0];
string message[0], encrypt[0];
int main()
{
cout << "Please enter your message."; //start with this
cin >> message[0];
int value = length(message[0]);
int count=0;
/*
store message as an array
loop through array, adding 13 to each value, use tolower() on each value
if value is
*/
for (int i=0; i < value; i++)
{
valueChange(message[i]);
if (message[i] == ' ') //checks for spaces in the string
{
spacePosition[count] = i + 1; //records the placement of spaces
//in the string
//have the array cast the i value to a new int value
//store space positions in an array
count++;
}
}
cout << "&";
cout << "Message encrypted and transmitted."; //final message
getch();
return 0;
}
int valueChange(int array[])
{
array[0] += 13;
if (array[0] > 122)
{
array[0] - 122;
}
return (array[0]);
}
int length(string array)
{
return (array.length() - 1);
}

If you need to search for spaces you can use string::find_first_of(string). You just need to write
`
std::string yourstring;
yourstring.find_first_of(" ");
`
then you need to iterate through the whole string using iterator.
And why are you declearing array if zero length? You can simply use simple std::string class. If you are not allowed to then simply use find_first_of(....) function available in standerd library. It basically returns the iterator to the first matching element.

int spacePosition[0];
string message[0], encrypt[0];
Probably want those to be 1's... or not use an array at all. But you are declaring arrays with 0 length, so yeah, you're going to segfault when you try writing to them.

Related

Reversing string using stack (static array) in c++

i am new to this concept in c++
i am trying to reverse string using stack static array implementation in c++.
Input: qwerty
expected output: ytrewq
output which i am getting is: trewq
Can some one explain me why is this happening and any possible solution.
Here's my code
#include <iostream>
#include <string>
using namespace std;
#define SIZE 10
string arr[SIZE];
unsigned a = -1;
void push(char ch) {
a = a + 1;
arr[a] = ch;
}
void pop() {
a = a - 1;
}
void display() {
for (int j = a; j >= 0; j--)
cout << arr[j];
}
int main() {
string str;
getline(cin, str);
for (int i = 0; i < (str.length() - 1); i++)
push(str[i]);
display();
}
Remove the "-1" in :
for(int i=0;i<(str.length())-1;i++)
Else your array doesn't contains the last character.
I made the test without the -1, it works well.
The condition "< str.length()" is enough to loop on all string caracter.
In similar case, use the debugger to see what contains your variable. In these case the variable "arr" don't contains the last input caracter.
You push everything on the stack, so the last element can be popped first. Then do popping to fill a reversed strng. The stack should be a char array.
As this is typically a task, the rest is your puzzle.
Pop typically gives you the top element as:
char pop() {
char ch = arr[a];
--a;
return ch;
}
The correct way to reverse a string would be to do:
std::reverse(str.begin(), str.end());
But I think this might be homework/study so look at your output. You are just missing the last letter. That suggests the upper limit of your loop is wrong doesn't it?

Why my c++14 program for removing repeated characters is giving extra characters in the ouput?

#include <iostream>
using namespace std;
int main(){
string s,str;
cin>>s;
int a[26]={0};
for(int i=0;i<26;i++){
int x=(int)s[i]-97;
if(a[x]==0){
a[x]++;
str+=s[i];
}
}
cout<<str<<endl;
return 0;
}
Input : geeksforgeeks
Ouput:geksfor
�
This is where i am getting some extra characters as ouput why i am getting like that?
Can anyone help me ?
Thanks in advance.
Your loop runs with i in range [0, 26), where i is indexing s, regardless of the length of s (and in this case, s is much shorter than 26 character long). Eventually, you index outside the bounds of s (invoking undefined behavior) and start processing gibberish, and your code starts pushing unique gibberish onto your result string. If you can assume your inputs are always lowercase ASCII, you could iterate with i in range [0, s.size()) (or use C++11 for-each style looping without indexing at all), but short-circuit out if str reaches a length of 26 (because all 26 unique characters have been seen).
One approach:
int main(){
string s,str;
cin>>s;
int a[26]={0};
for(auto c : s){
int x = c-97;
if (a[x] == 0) {
a[x]++;
str += c;
if (str.size() == 26) break;
}
}
cout<<str<<endl;
return 0;
}
I think you have consider the input string in lower case letters.
But one mistake you have done in the code is that you are iterating the for loop for only 26 times.
But lets consider the string such that the letters are repeated after 26th character. There only your code fails. So, you just have to iterate through the whole string.
The correct code is:
#include<iostream>
using namespace std;
int main()
{
string s,str;
cin>>s;
int a[26]={0};
for(int i=0;i<s.size();i++)
{
int x=(int)s[i]-97;
if(a[x]==0)
{
a[x]++;
str+=s[i];
}
}
cout<<str;
return 0;
}

Iterate over a string and fill an array in C++

I'm working on this code that iterates over a string--that is actually a string representing an integer in this case--and fills an array with each "digit" of the string. So string "350" would result in an array with elements {3,5,0}.
Here is the code:
#include <stdlib.h>
#include <iostream>
using namespace std;
int main() {
int arr[5];
string test = "10000";
for(unsigned int i = 0; i<test.length(); i++) {
char c = test[i];
cout << c << endl;
arr[i] = c;
}
//printing the array for testing
for (int i = 5 - 1; i >= 0; i--)
cout << arr[i];
return 0;
}
char c = test[i];
arr[i] = c;
}
return 0;
}
The issue is that array that results from this is {49,48,48,48,48}. I have no idea why its doing that and where I have gone wrong with the code. Why is it adding the numbers 49 and 48, and how can I fix this?
Also if it helps anyone, here is a link to a stepper running through the code:
http://pythontutor.com/visualize.html#code=%0A%23include%20%3Cstdlib.h%3E%0A%23include%20%3Ciostream%3E%0A%0A%0Ausing%20namespace%20std%3B%0A%0A%0A%0Aint%20main%28%29%20%7B%0A%20%20int%20arr%5B5%5D%3B%0A%09string%20test%20%3D%20%2210000%22%3B%0A%20%20for%28unsigned%20int%20i%20%3D%200%3B%20i%3Ctest.length%28%29%3B%20i%2B%2B%29%20%7B%0A%20%20%20%20char%20c%20%3D%20test%5Bi%5D%3B%20//this%20is%20your%20character%0A%20%20%20%20arr%5Bi%5D%20%3D%20c%3B%0A%7D%0A%09return%200%3B%0A%7D%0A%0A%0A&cumulative=false&curInstr=19&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=cpp&rawInputLstJSON=%5B%5D&textReferences=false
What you see in your array are the ascii for the characters your insert.
Here is what you should do to convert your character to an integer:
arr[i] = atoi(&c);
The 48 and 49 are your 0 and 1 in ascii. You need to convert from ascii to digits.
You created arr as an array of integers, thus by assigning character elements to it you implicitly cast them to an integer. When you do this, the ASCII value of the characters is printed, instead of the characters themselves. You should use an array of characters instead.
char arr[5];

Reading digits on separate lines in a txt.-file to an array in C++

In order to solve Euler Project 8 without resorting to a "Big Number" library, I would like to read the separate digits in an txt.-file to separate spots in an array. The digits in the txt.-file are arranged as follows:
094239874......29837429837 [50 of them],
192319274......12837129873 [50 of them]
such that there are in total 20 lines with 50 digits, all separated by enters. So I am trying to write a program which writes the first digits to the first spot in the array and continues this process (paying attention to the spaces) until the 1000th digit. I have tried finding solutions to this problem in tutorials and elsewhere online, but I cannot make it work for this specific example. Up to now I have something like
int main() {
int array[999];
string trial[999];
ofstream myfile;
myfile.open ("example.txt");
for(i=1 ; i<=1000 ; i++) {
myfile >> trial;
// Somehow convert string to int as well in this loop?
}
You can try to do it this way (first read the file contents into a string, then convert each char to an int, btw you should use a vector<int> instead of a raw array):
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
string total;
ifstream a_file("data.txt");
while (getline(a_file, str))
total += str;
vector<int> vec;
for (int i = 0; i < total.size(); i++)
{
char c = total[i];
int a = c - '0';
vec.push_back(a);
}
}
You can read your file line by line, then add your digits to an array like this way:
// out of your loop
std::vector<int> digits;
// in your loop
std::string buffer = /*reading a line here*/;
for (auto c : buffer) {
digits.push_back(c - '0');
}
Furthermore, STL containers are better than C-style arrays (std::vector / std::array).
I suppose this is what you're looking for
int main(void)
{
unsigned char numbers[20][50];
FILE *pf = fopen("example.txt", "r");
for(int i = 0; i < 20; i++)
{
// read 50 characters (digits)
fread(&numbers[i], 1, 50, pf);
// skip line feed character);
fseek(pf, 1, SEEK_SET);
}
fclose(pf);
// conversion from ascii to real digits by moving the digit offset (subtracting by the first digit char in ascii table)
for(i = 0; i < 20*50; i++)
((unsigned char*)numbers)[i] -= (unsigned char) '0';
// the digits are now stored in a 2-dimensional array (50x20 matrix)
return 0;
}
This approach will not work. According to this question, any built-in integral type is likely to be too small to represent the value of a number with 50 decimal digits.

How to parse a user's input and store each individual character as a string

Okay so I'm working a calculator program that takes in a user input(ex. "(3+(4+12))"), and I need to parse the user's input and store it in an array of strings but I am having trouble doing so. My code currently is this
void parseInput(string input) {
vector <string> input_vector;
for(int i = 0; i < input.size(); ++i) {
if(isdigit(input.at(i)) == 0 && isdigit(input.at(i + 1)) == 0) {
++i;
input_vector.push_back((input.at(i) + input.at(i+1)));
}
else {
input_vector.push_back(input.at(i));
}
}
for(int i = 0; i < input_vector.size(); ++i) {
cout << endl << input_vector[i];
}
}
I know my problem is coming from trying to add a char to an vector of strings, but how would I get each char in the string and keep it as a string to store into my vector. Or is there a better way to parse this out??
edit
Okay so what I am having the most trouble with is the problems that come from the 12 splitting up into two separate chars "1 * 2" How would I go about so that it represents 12 and doesn't split it up???
Here is a solution (using c++11):
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
int main() {
std::string const input = "(3+(4+12))";
std::vector<std::string> chars(input.length());
// Maps each character of `input` to `std::string`
// with that character and saves the results in
// corresponding position in `chars` vector:
std::transform(input.cbegin(), input.cend(), chars.begin(),
[](char c) {
// One of the ways to cast `char` to `std::string`:
return std::string(1, c);
});
// To be sure it works properly, it prints
// generated strings:
for (size_t i = 0; i < chars.size(); ++i) {
std::cout << chars[i];
}
std::cout << std::endl;
}
The answer is u need to split the string into tokens, i have given an example which will add 4 to 12, to make it 16, but think that the string does'nt have any brackets, suppose if the user entered 4+12 and u need to add it you can do the following:
char string[10], nstr[10];
int p=0, a=0, b=0, op=0;
cin>>string; // input string
While (string[i]!='+' || string[i]!='-')
{
nstr[p]=string[i]; // copy the contents of string to nstr.
p++;
i++;
}// loop exits if the string[i] reaches to the operator (+/-*).
nstr[p]='\0';
a=atoi(nstr);// convert the string to integer.
op=i;// this will hold the position of array of the operator in the string.
i++;
p=0;
while (string[i]!='\0')
{
nstr[p]=string[i];// this will copy the contents of the string after the operator.
i++;
p++;
}
nstr[p]='\0';
b=atoi(nstr);
if (string[op]=='+')// check what the user want to do. Add/subtract/divide etc.
c=a+b;
else if (string[op]=='-')
c=a-b;
This program is not tested but will work, if not then use the logic in your program, like i did in my program, this will not take 1 and 2 sepratly, instead it will take 4 and 12, you can type more charaters but is limited to long, i used int here to get the return value of atoi(), hope this helps u...