int main()
{
cout<<"Enter a word"<<endl;
char word1[]={0}; //first char array initialization
cin>>word1;
cout<<"Enter another word"<<endl;
char word2[]={0}; //second char array initialization
cin>>word2;
char word3[]={0};
char word4[]={0};
int i=0;
while (word1[i]!='\0') //this converts both words to lower case by usinction tolower
{
word3[i]=char(tolower(word1[i])); //word3 and word4 stores the new arrays
word4[i]=char(tolower(word2[i]));
i++;
}
int output; //output stores the value of 0,1 or -1
output=compareString(word3,word4);
if (output==0)
{
cout<<"The two words are the same."<<endl; //if arrays are same
}
if (output==1)
{
cout<<"the 1st character of 1st word has a larger value than of 2nd word."<<endl;
}
if (output==-1)
{
cout<<"the 1st character of 2nd word has a larger value than of 1st word."<<endl;
}
return 0;
}
int compareString(char string1,char string2)
{
int size1=0; //initialize size of string1
int j=0; //string1 position initialize
while (string1[j]!='\0') //loop to determine size of string1
{
size1+=1;
j+=1;
}
int a=0; //initialize size of string2
int size2=0; //string2 position
while (string2[a]!='\0') //loop determines size of string2
{
size2+=1;
a+=1;
}
int i=0;
int k=0;
for (i=0;i<size1;i++) //loop to compare the two strings
{
if (string1[i]!=string2[i])
{
if (string1[i]>string2[i]) //comparing 1st character of string1 & string2
{
return 1;
}
else //if string2's first character is greater in value
{
return -1;
}
}
else
{
k++; //incrementing k when character of string1 matches string2 character
}
}
if (k==size1) //to cjheck if all characters of both strings are same
{
if (k==size2)
{
return 0;
}
}
}
This is a function which compares two char arrays and returns 0 if characters correspond to each other,returns 1 if first character of string1 is greater than first character of string2 in value and returns -1 if first character of string1 is less than first character of string2.The problem is that when i run it,even when the two words are different,the output is always 0 and the text "The words are the same" appears.
Am i initializing the two arrays correctly in my main program?or is there some other problem?
This declaration
char word1[]={0};
declares an array of size 1, meaning when you do your input it will overwrite the stack. The same for all other arrays.
When dealing with string in C++ it is highly recommended to use std::string!
char word1[]={0};
This line creates an array word1 that has exactly one element, set to 0. When using this array to hold a string, you cannot hold anything in this except the empty string. You are causing a buffer overflow here, because you read a non-empty string into this array, which will then write into other parts of memory not allocated to this array. This is very bad.
Consider using std::string to hold strings instead. It will automatically resize its allocation as necessary.
Related
I am learning c++, I write some code to convert a string to uppercase and display it. I assign a string str with "asdf" and then create a char array pointer and allocate a length same as that of the string.
But after I assign indices of char array with uppercase chars when I try to display char array there are many junk characters appended to the end. Why does this happen as I have only allocated the char array with a size = "length of string" then how does char array have junk chars at the end even after the actual allocated size.
string str{ "asdf" };
char* str_c = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
cout << str_c; // displays ASDF²▌r┐│w²A∙
Your char array needs to be one character longer than the length of the string, for the null terminator
string str{ "asdf" };
char* str_c = new char[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
str_c[str.length()] = '\0';
cout << str_c; // displays ASDF
In C-style strings (char*) the length of the string is not stored in memory. Thus, it must use some other way to determine where the string ends. The way it does that is by assuming that the string is all the bytes until the byte that is equal to zero (so-called null-terminator).
Without explicitly allocating an extra byte for the null terminator, and setting it, your string continues with the garbage that happens to be after the bytes you have allocated until it encounters (accidentally) the nearest 0.
// I have to input a line of text into a c-string and then convert each word into a pointer in an array of pointers.
// I can get the line of text using cin.get() but do not know how to proceed.
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototypes
void get_input(char *array, int size); // gets paragraph as input and assigns it to char array
int main()
{
const int SIZE = 256; // holds size of char array
const int POINTER_SIZE = 20; // holds 20 pointers in array of pointers
char paragraph[SIZE]; // initialize array to hold paragraph
get_input(paragraph, SIZE);
}
// Function Definitions
void get_input(char *array, int size) {
cout << "Enter a paragraph: ";
cin.getline(array, size);
}
// I need the line of input to be broken up into individual strings and stored as an array of pointers to each word.
After reading the input into your array, you can iterate through the array, and setting a pointer to the first character of each word.
char* word[100];
// Assuming the first character is the beginning of a word
word[0] = ¶graph[0];
int c = 1;
int i = 1;
while(paragraph[i] != '\0'){
// If the character was a letter
if((paragraph[i] >= 65 && paragraph[i] <= 90) || (paragraph[i] >= 97 && paragraph[i] <= 122)){
// If the previous character was not a letter
if(!(paragraph[i-1] >= 65 && paragraph[i-1] <= 90) && !(paragraph[i-1] >= 97 && paragraph[i-1] <= 122)){
word[c] = ¶graph[i];
c++
}
}
i++;
}
You can also use a vector of char* arrays to store the words and splice the words through non-letter characters and then generate a pointer for each item in the vector.
you can use c_str() function to exchange
`
The asked program was to input two string and print their respective size as first line in output while the second line contains the concatenation of two string and the third line of output contains the original string after the first character of both the string have been swapped..below is my code..everything is working except while printing the second string it is printing unnecessary characters because of which entire second string is not being printed
PS: i'm new to c++
int main()
{
string a,b,c;
cin>>a>>b;
int j=a.size();
int k=b.size();
char s[j],p[k];
cout<<a.size()<<" "<<b.size()<<endl;
c=a+b;
cout<<c<<endl;
for(int i=0;i<a.size();i++)
{
s[i]=a[i];
}
for(int i=0;i<b.size();i++)
{
p[i]=b[i];
}
char t;
t=s[0];
s[0]=p[0];
p[0]=t;
cout<<s<<" ";
cout<<p;
return 0;
}`
input:
dlxecxsye
bfjoosgukxgywz
output:
9 14
dlxecxsyebfjoosgukxgywz
blxecxsye
# dfjoosgukxgywz
desired output:
9 14
dlxecxsyebfjoosgukxgywz
blxecxsye dfjoosgukxgywz
Your string p is of size k, which is size of input b (14).
In your for cycle you iterate from 0 to size of input a (9), which in your case is smaller than size of input b.
When you output content of p at the end of your code, chars at indexes from 9 to 13 are not set and you print something undesired from that place in a memory.
I don't understand the need for the character arrays.
// Swapping first characters
char temp = a[0];
b[0] = a[0];
a[0] = temp;
Please use the debugger and verify that your character arrays are terminated by a nul character.
See also: std::string::c_str() and strncpy.
Im trying to take the string the user enters which will then clean it up a bit and store word by word in a dynamically allocated array. The array points to a struct. Im trying to store the array in the "English" struct variable.
Here is what i came up with but when i run the code my test cout of the array shows no output so i feel as the words are not being copied to the array.
//This program will take in a English sentence from the user where it will then store the string in an dynamically allocated array
//where it will be run through a functions which will convert the English sentence to pig Latin. The
//final sentence will be displayed to the screen for the user to see.
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
struct Word{
string english;
string piglatin;
};
Word * sentenceSetup(string, int &);
int main()
{
int Size=1;//default how many words in the sentence.
string userSent;
//ask the user for a sentence they want to convert
cout<<"Hello, please enter a string to convert to PigLatin: "<<endl;
getline(cin, userSent);
Word * arr = sentenceSetup(userSent,Size);
for (int i=0; i<Size;i++)
{
cout<< arr[i].english<<endl;
}
return 0;
}
//**************************************************************
//sentenceSetup Definition: In this function we will be asking *
//the user to enter in a string which then will be counted *
//for how many words it has and creating an array of structs *
//big enough to hold that string. The array will then be *
//returned to the calling function. NOTE: This function should *
//remove all capitalization and special characters except for *
//the end period, exclamation mark, or question mark. *
//**************************************************************
Word * sentenceSetup(string userSent, int &size)
{
char nextCharacter;
//check the input for any unwanted special characters not listed in the function def.
for( int i=0; i<int(userSent.size()); i++)
{
nextCharacter = userSent.at(i);
if(ispunct(userSent[i]))
{
userSent.erase(i--, 1);
}
}
//change the whole sentence to lower case
for (int i=0; i<int(userSent.size()); i++)
{
userSent[i]=tolower(userSent[i]);
}
//Check each character in the string to see if it is a space. If the loop
//notices a space then a space equals a word in the string.
for (int i =0; i<int(userSent.size());i++)
{
nextCharacter = userSent.at(i); //Reads the character
if(isspace(userSent[i]))
{
size++;
}
}
//test to see if num count works
cout<<"There is "<<size << " words in the sentence."<<endl;
//test to see if special characters removed
//cout<<userSent<<endl;
//allocate an array to store the words in for the struct Word
Word *temp= new Word[size];
int count =0;
string word;
for(count=0;count<size;count++)
{
if(isspace(userSent[count]))
{
word =userSent.substr(0,count);
temp[count].english=word;
userSent.erase(0,count);
}
}
//test
for(count =0; count<size;count++)
{
cout<<temp[count].english;
}
return temp;
}
The problem lies in how you are trying to write the data into dynamically allocated Word* temp variable as well as the for loop you are using for the same. The above code needs to be rectified as follows
I'm creating a main array of strings which will be returned by the function
//allocate an array to store the words in for the struct Word
Word *main= new Word[size];
int count =0;
string word;
//Variable to keep track of start of each word
int start_count =0;
//Create a temp pointer to iterate through the memory allocated for each word
Word *temp = main;
//Variable to keep track of length of each word
int bytes_to_cpy =0;
The for loop should loop until the length of the sentence, not just the number of words
for(count=0;count<=userSent.length();count++){
if(isspace(userSent[count]))
{
//Copy the required bytes as a substring
word =userSent.substr(start_count,bytes_to_cpy);
//Copy the word to the main array
temp->english=word;
//Increment the pointer;
temp++;
//Ignore the white space for the next word
start_count=count+1;
//Reset the length of the word
bytes_to_cpy=0;
}
//Count the length of the word
bytes_to_cpy++;
}
//Add the last word to the array
word =userSent.substr(start_count,userSent.length()-start_count);
temp->english = word;
temp = main;
//test
for(count =0; count<size;count++)
{
cout<<temp->english<<endl;
temp++;
}
return main;
Apart from this, you also need to take care of multiple whitespaces, whitespace at the beginning and at the end of the user input string in our Function that calculates the number of words. Your current implementation does not take care of these.
So I found this code on the internet, but as I'm not that familiar with C++. I found difficult to understand this: how does a vector suddenly becomes a matrix?
int main(){
int n;
string v[MAX];
cin >> n;
for(int i=0;i<n;i++)
cin >> v[i];
for(int i=0;i<n-1;i++){
int y1,y2;
y1=v[i].size();
y2=v[i+1].size();
for(int j=0; j<y1 && j<y2 ;j++)
if(v[i][j]!=v[i+1][j]){ // here <-
int x1,x2;
x1=(int) v[i][j]-'A';
x2=(int) v[i+1][j] - 'A';
m[x1][0]=true;
m[x2][0]=true;
m[x1][x2+1]=true;
break;
}
}
string v[MAX];
is an array of std::string (presumably - this is one reason to avoid using namespace std;. How do I know what type of string it is?).
You can access elements of an array with []:
int someInts[5];
someInts[3]=1000; // sets the 4th int (counting starts from 0)
You can also access characters in a std::string with []:
std::string name("chris");
std::cout << name[3]; // prints 'i'
So you can access the letters in an array of std::strings with two sets of []:
std::string names[10]; // 10 names
names[3] = "chris"; // set the 4th name
std::cout << names[3][1]; // prints 'h'
// ^ access letter in string
// ^ access string in array
Here is a self-explanatory example
int main()
{
std::string name;
name = "test";
for(int i = 0; i<4; i++)
std::cout<<name[i]<<std::endl;
std::cout << "Hello, " << name << "!\n";
}
It will print
t
e
s
t
Hello, test!
So, an array of strings is actually a 2D array of characters, that you called a matrix.
string v[N] is an array of string, string itself is an array of chars.
Since, as the commentor pointed out, there are neither vectors or matrices in the code you gave, I'll make a couple assumptions:
By "vector", you mean "array"
You think that double square brace operators ([][]) indicate a matrix.
If those are both true, I can explain what you're seeing:
string[5] strings = { Some Strings... }
//The first string in the array
string string1 = strings[0];
//The first letter of the first string
char char1 = string1[0];
//The above is the same as:
char char1Again = strings[0][0];
In the line above, the first square bracket operator returns the first string in the array. The second square bracket operator is then applied to that string, which returns the first character of that string.
This works because both arrays and Strings (which are really arrays themselves deep down) implement the square bracket operator to access their internal elements by index.
Technically, in a convoluted way, you could call this a matrix, but "2D array of characters" would be more appropriate.