Why is the output of the string 'text2' blank? - c++

'text1' is a sentence. I want 'text2' to contain the first word of the sentence in 'text1' (all letters before the first space).
The code gets compiled successfully, but, when executed, nothing gets printed on the screen.
Below is the code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,k,c;
bool done=false;
string text1,text2;
getline(cin, text1);
for(i=0; i<text1.size(); i++)
{
if(text1[i]==' ' && done==false)
{
c=i;
for(k=0; k<i; k++)
{
text2[k]=text1[i-c];
c--;
}
done=true;
}
}
cout<<text2<<endl;
return 0;
}

you can't do text2[k]=text1[i-c] as text2 is empty, you need to resize it first.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,k,c;
bool done=false;
string text1,text2;
getline(cin, text1);
for(i=0; i<text1.size(); i++)
{
if(text1[i]==' ' && done==false)
{
c=i;
text2.resize(i);
for(k=0; k<i; k++)
{
text2[k]=text1[i-c];
c--;
}
done=true;
}
}
cout<<text2<<endl;
return 0;
}

Use text2.push_back(text1[i-c]) (API), because indexing into an empty string (which is what text2 is) with text2[k] invokes undefined behavior. That indexing operation doesn't change the length of text2 (or its contents).

Related

Why do these perfectly similiar codes not work?

I'm learning about functions in C++ and I saw this code on Tutorialspoint which tells us whether the
input is an int or a string.
Link to the Tutorialspoint article : https://www.tutorialspoint.com/cplusplus-program-to-check-if-input-is-an-integer-or-a-string
This is the original code:
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main() {
string str = "sunidhi";
if (check_number(str))
cout<<str<< " is an integer"<<endl;
else
cout<<str<< " is a string"<<endl;
string str1 = "1234";
if (check_number(str1))
//output 1
cout<<str1<< " is an integer";
else
//output 2
cout<<str1<< " is a string";
}
The original one works perfectly fine, but my code either only shows ouput 1 or only shows output 2 no matter whether you enter an int or a string.
My code:
Note : my code was written on an online compiler. Link to the compiler : https://www.onlinegdb.com
#include <iostream>
using namespace std;
//the function which checks input
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i]) != true)
return false;
return true;
}
//driver code
int main(){
string str = "9760";
if(check(str)){
//output 1
cout<<"Thanks! the word was " <<str;
}
else{
//output 2
cout<<"Oops! maybe you entered a number!";
}
}
Ouput when executing my program : Thanks! the word was 9760
Link to the code project: https://onlinegdb.com/HkcWVpFRU
Thank you!
You are checking if the char is a digit and returning false if it is, you should change it to
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i])
return false;
return true;
}
a sidenote, if you want to check for false you can do (!bool) instead of (bool != true) it looks cleaner

Checking if alphabetic string is a palindrome in C++

I've attempted to write a code that checks whether or not a string is a palindrome. Here is the code:
#include <iostream>
#include <string>
using namespace std;
bool pal(string str)//This block of code checks if input string is a palindrome
{
bool valid;
int i;
for (i = 0; i < str.length(); i++)
{
if (str[-i] == str[i])
{
valid = true;
}
else
{
valid = false;
}
}
return valid;
}
int main()
{
string s;
cin >> s;
if (!pal(s))
{
cout << "NO" << endl;
}
else
{
cout << "YES" << endl;
}
return 0;
}
Currently I am getting "Debug Assertion Fail" error.
str[-i] == str[i]
is a problem since negative indices are not valid indices in C++.
You need to change the strategy a little bit.
bool pal(string str)
{
int i = 0;
int j = str.length() - 1;
for ( ; i < j; ++i, --j)
{
if (str[i] != str[j])
{
// No need for any more checks.
return false;
}
}
// If we come here, the string is a palindrome.
return true;
}
C++ Provides us with an inbuilt function reverse() which can be used to reverse the Input string and compare it with un reversed string and print the output. The code goes as follows.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
string str;
cin>> str;
string rev;
rev = str;
reverse(str.begin(), str.end()); // string reverse operation
if(rev == str){
cout<<"YES"<<endl; // Prints "Yes" if string is palindrome
}else{
cout<<"NO"<<endl; // Prints "No" if string is not palindrome
}
return 0;
}

Why my character array(string) is breaking?

I have written a code to copy from first string's element to second string except space.it simply takes input and if it gets a space then it doesn't insert character of first string into second string. when i am printing second string at the last,the string is partially broken up. But instead of space,if i put any character the second string fully prints out.I am trying but could you fix my bug please?
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
char str1[100];
while(cin>>str1)
{
char str2[100];
int k=0;
for(int i=0; str1[i]!='\0'; i++)
{
if(str1[i]!=' ')
{
str2[k] = str1[i];
k++;
}
}
str2[k] = '\0';
cout<<"result is "<<str2<<endl;
}
return 0;
}
You can use gets() and puts() to read/display a string:
#include <iostream>
#include <string.h>
using namespace std;
int main(void)
{
char s1[100], s2[100];
int k=0;
puts("Insert your string:");
gets(s1);
for (int i=0; i<strlen(s1); i++) {
if (s1[i] != ' ') {
s2[k]=s1[i];
k++;
}
}
puts(s2);
}

C++ reading string segmentation fault

I am writing a program that will input an alphabetic message, and use the class to build the morse code string, and then output the string. I have written all the method and the program compiles fine. However when I enter the temp string and hit return. I am given a segmentation fault. I can't seem to find the problem. If anyone can see what the problem is I would greatly appreciate your help. Thanks.
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class Code
{
public:
Code(); // Default constructor - loads and uses morse code
string decode(vector< string> message); // decodes a message
string encode(vector<char> message); // encodes a message
private:
vector<string> codewords; // this is a codeword vector parallel to A-Z
vector<char> alpha; // this is the vector for A-Z
vector<char> alphacode(); // function builds the vector alpha - A B C etc.
vector<string> morsecode(); // function builds the vector codewords containing morse code
char decode(string c); //returns the character for the codeword c.
string encode(char c);
};
Code::Code() {
alpha = alphacode();
codewords = morsecode();
}
string Code::decode(vector< string> message) {
string temp;
for (int i=0; i < message.size(); i++) {
temp += decode(message[i]);
}
return temp;
}
string Code::encode(vector<char> message)
{
string temp;
for (int i=0; i<message.size(); i++)
{
temp+=encode(message[i]);
}
return temp;
}
vector<string> Code::morsecode()
{ // This function returns a vector containing the morse code
vector<string> temp(28);
temp[0] =".-";
temp[1] ="-...";
temp[2] ="-.-.";
temp[3] ="-..";
temp[4] =".";
temp[5] ="..-.";
temp[6] ="--.";
temp[7] ="....";
temp[8] ="..";
temp[9] =".---";
temp[10] ="-.-";
temp[11] =".-..";
temp[12] ="--";
temp[13] ="-.";
temp[14] ="---";
temp[15] =".--.";
temp[16] ="--.--";
temp[17] =".-.";
temp[18] ="...";
temp[19] ="-";
temp[20] ="..-";
temp[21] ="...-";
temp[22] =".--";
temp[23] ="-..-";
temp[24] ="-.--";
temp[25] ="--..";
temp[26] =".......";
temp[27] ="x";
return temp;
}
vector<char> Code::alphacode()
{// This returns a vector containing the alphabet a-z and " "
vector<char> temp;
for (char c='A'; c<='Z'; c++)
temp.push_back(c);
temp.push_back(' ');
temp.push_back('.');
return temp;
}
char Code::decode(string c)
{
for (int i = 0; i < alpha.size(); i++) {
if(c == codewords[i]) {
return alpha[i];
}
}
}
string Code::encode(char c)
{
for (int i=0;i<codewords.size();i++)
{
if (c==alpha[i])
{
return codewords[i];
}
}
}
int main()
{
vector<char> message;
string temp;
getline(cin, temp);
for (int i=0; i <temp.length(); i++)
{
message.push_back(temp[i]);
}
Code C;
cout << C.encode(message) << endl;
}
Your alphacodes and morsecodes are only for Capital letters, so this function returns null resulting in problems.
string Code::encode(char c)
{
for (int i=0;i<codewords.size();i++)
{
if (c==alpha[i])
{
return codewords[i];
}
}
}
Your check for c==alpha[i] should either check ignoring the case or your alpha codes should have small alphabet codes as well. Your morsecodes should have the codes for small alphabets as well and your checks where you map A-Z to 0-28 should accommodate small letters.
Remember, small letters have different ASCII codes than Capital letters.
The following function does not have a return statement at the end.
string Code::encode(char c)
{
for (int i=0;i<codewords.size();i++)
{
if (c==alpha[i])
{
return codewords[i];
}
}
// What should happen if execution gets to this line?
}
If, per chance, your code reaches the end of the function, you will run into undefined behavior. That could be the source of your problem.

how to decleare a 1D double array

Data input from the keyboard.The length of array maybe very long.
I want to finish inputing when press ENTER twice.
the numbers separated by space, tab or ",". how to detect the length n?
I have tried like this:
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
void main()
{
bool flag=true;
unsigned n=0,i;
double x;
string line,str;
istringstream iss;
cout<<"input your numbers."<<endl;
count<<"Press the Enter key twice finish data inputting."<<endl;
while(flag)
{
getline(cin,line);
str+=line+' ';
if(line.empty())
flag=false;
}
// get the length n
iss.str(str);
while(iss>>x)
{
n++;
}
double *v=new double[n];
iss.seekg(0);
for(i=0;i<n;i++)
iss>>v[i];
for(i=0;i<n;i++)
{
cout<<v[i];
if(i<n-1)
cout<<' ';
}
cout<<endl;
delete []v;
}
I am a novice. Help me, Please!
Try this After taking the input in variable line do this:
#include<iostream>
#include<string>
#include<sstring>
using namespace std;
void main()
{
bool flag=true;
unsigned n,i=0;
double x;
string line,str;
istringstream iss;
cout<<"input your "
getline(cin,line);
int c=0;
char * pch;
pch = strtok (line," ,");// this will work for space and comma but you can add your own specifiers
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,");
c++;
}
return(c);// will give the length of arry.
}
Man to declare 1D array
the syntax is
void main()
{
int array[5];
//to initalize;
for(int i=0;i<5;i++)
{
array[i]=i;
}
for(int i=0;i<5;i++)
{
cout<<array[i]<<" ";
}
// and to declare dynamically
int * array=new int[5];
}
I have solved this problem.
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
void main()
{
bool flag=true;
unsigned n=0,i;
double x;
string line,str;
istringstream iss;
cout<<"input your numbers."<<endl;
cout<<"Press the Enter key twice finish data inputting."<<endl;
//Brecause data may come from clipboard and have multi line.
while(flag)
{
getline(cin,line);
str+=line+'\n';
// vc++ 6.0 have a bug in include file: STRING. You shoud fix it.
//Or you shoud press ENTER more than twice to terminate inputing.
//Replace I.rdbuf()->snextc(); to _I.rdbuf()->sbumpc();
if(line.empty())
flag=false;
}
// get the length n
iss.str(str);
while(iss>>x)
{
n++;
}
double *v=new double[n];
iss.clear();// very important.
// initialize v[n]
iss.str(str);
for(i=0;i<n;i++)
iss>>v[i];
// output v
for(i=0;i<n;i++)
{
cout<<v[i];
if(i<n-1)
cout<<' ';
}
cout<<endl;
delete []v;
}