Making array (char) 1 gives error on stdio.h - c++

I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.

Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.

Related

I am just trying to use the getline function as an absolute beginner. I still dont know what went wrong here

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
constexpr auto MAX_NUM_LEN = 10;
int main() {
string a_num[MAX_NUM_LEN];
cout << "Type your full ID" << endl;
cin.getline(a_num, MAX_NUM_LEN, '.');
cout << "\nyour input is: " << a_num;
}
Link to my embedded image of the program i did in VS code
[1]: https://i.stack.imgur.com/TM7BC.jpg
Use char a_num[MAX_NUM_LEN]; instead of string a_num[MAX_NUM_LEN];
Your code will run.
when you use cin.getline() function, then its first parameters would be either a constant character pointer or a character array name.
Please check following resources to learn more about getline
std::getline (string)
getline (string) in C++
C++ program to read string using cin.getline()
std::cin.getline( ) vs. std::cin

Sort char array using sort function c++

I am trying to limit user input into alphabet only, then sort all the character in ascending order.
build messages
error: no matching function for call to 'std::__cxx11::basic_string::basic_string(char&)'
This is my header
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
#include <regex>
should i convert the char into string then convert back to char for my following code ?
string Sortstr (str[mlength]);
sort(Sortstr.begin(), Sortstr.end());
getting this 2 line error.
int mlength = 100;
int main() {
char str[mlength];
int length;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'\n');
regex pass1("^[a-zA-Z]+");
while(!regex_match(str,pass1)) {
cout<<"Error"<<endl;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'\n');
}
string Sortstr (str);
sort(str, str + strlen(str));
}
Why not just sort str?
sort(str, str + strlen(str));
There's no reason you can't sort an array directly. Just pass pointers to the first and one-past-the-end elements of your array to sort. In this case adding strlen gets a pointer to the effective end of your array.
In this line
string Sortstr (str[mlength]);
you are using the index operator on a char array which gives you one single char. So, you are passing one single char to the string constructor. This constructor does not exist, hence the error. Even if it existed, you do not want to pass one single char but the entire char array.
What you want is this:
string Sortstr (str);

Character Array of dynamic length

I have written a C++ Function which can be represented as below:
All it does is take a string (this is where it crashes) and reverse it.
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"Enter a string: "<<endl;
char *str;
gets(str);
cout<<"Reversed String is: ";
for(int i=strlen(str)-1;i>=0;i--)
cout<<(str[i]);
return 0;
}
I guess there's some kind of memory access violation.
Any clue why this doesn't work?
Error: Segmentation fault (core dumped)
In c++ there is way more easier and less error prone solution to this problem via std::reverse from algorithm. Also its easier to use std::string.
#include <iostream>
#include <algorithm>
int main ()
{
std::string input;
std::cout << "Enter string to reverse: ";
std::cin >> input;
std::reverse(input.begin(),input.end());
std::cout << "Reversed string: " << input << std::endl;
return 0;
}
If you have to do it via char arrays, try this (you dont even need dynamic memory allocation)
#include <iostream>
#include <algorithm>
#include <cstring>
int main ()
{
char input[1024];
puts("Enter string to reverse: ");
fgets(input, 1024, stdin);
std::reverse(input, input + strlen(input));
printf("Reversed string: %s", input);
return 0;
}
Your code isn't c++ style and I recommend you take a look at the answer from Filip (https://stackoverflow.com/a/45903067/4386427)
I'll just address what goes wrong with your code.
When you do
char* str;
all you get is a pointer that can point to a char. You don't get any memory for holding a char. Further the value of the pointer variable str is uninitialized.
So when you do
strlen(str)
you read an uninitialized variable and try to treat this uninitialized value as a C-style string. That is undefined behavior and is very likely to cause a program crash.
You need to make sure that str is initialized before using it. As you want dynamic memory, you could do:
char *str;
str = new(char[100]); // Initialize str to point to a dynamic allocated
// char array with size 100
...
...
delete(str);
But again - I wouldn't use this style in c++ code

different definitions of string changes answer

I've started learning C++ from HackerRank.
st.first_name outputs concatenated strings(first_name and last_name) when they are defined like char first_name[50]; and char last_name[50];. But when i define them like string first_name; and string last_name; output is fine. Why is it so?
Here is the code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
add code for struct here.
*/
struct Student
{
int age;
//char first_name[50];
//char last_name[50];
string first_name;
string last_name;
int standard;
};
int main() {
Student st;
cin >> st.age >> st.first_name >> st.last_name >> st.standard;
cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;
return 0;
}
Here is the link to this question on HackerRank:
https://www.hackerrank.com/challenges/c-tutorial-struct
input for which i'm getting contradicting output:
11
lwpxiteeppsacowpnbxluqpmasgnwefzcsvrjxxammuqcftzgn uinkydgppulchupyrlwvbisdtqurfcsbaobgtplvvlxbxgltk
10
expected output:
11
lwpxiteeppsacowpnbxluqpmasgnwefzcsvrjxxammuqcftzgn uinkydgppulchupyrlwvbisdtqurfcsbaobgtplvvlxbxgltk
10
my output: 11 lwpxiteeppsacowpnbxluqpmasgnwefzcsvrjxxammuqcftzgnuinkydgppulchupyrlwvbisdtqurfc‌​sbaobgtplvvlxbxgltk
uinkydgppulchupyrlwvbisdtqurfcsbaobgtplvvlxbxgltk
10
In C++ C-style strings (using arrays of char) need a special terminator character, '\0'. This of course take up a character and you need to include that in the array you allocate. If you don't have space for the terminator it will be written out of bounds and you will have undefined behavior.
That's why you really should use std::string when programming in C++, you don't risk buffer overflows.
If you need to use C-style strings and arrays of char you need to add an extra character to your arrays to make space for the terminator. So if you want to allow the users to enter 50 characters, then you need an array of 51 characters. But beware, C++ has no bounds-checking so if the user enters a string longer than 50 characters you will still write out of bounds.

Store individual words from file into an element in string class array (C++)

I am trying to insert several string class arrays (taken from an input file) within a string class array.
The program I am writing consists of a Dictionary class in which the default constructor takes in a filename (eg."words.txt") as a parameter, and thereby stores each individually read word into a single element in a String class array.
The text file would look something like:
example
text
file
here
etc...
The code I have written to test it out so (which is not working at all) is below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Dictionary(const char *file) {
public:
string wordList;
int numWords;
};
Dictionary::Dictionary(const char *file) {
ifstream inFile;
int SIZE = 50000;
char pass[SIZE+1];
numWords = 0;
inFile.open(file);
if(!inFile)
cout << "File can not be opened" << endl;
else
while(inFile.getline(pass, SIZE)){
wordList[numWords] = pass[SIZE+1];
numWords++;
}
}
inFile.close();
cout << wordList[5] << endl;
cout << numWords << endl;
}
int main(){
Dictionary *foo = new Dictionary("words.txt");
};
The code compiles but prints:
//should print out the 5th word in the file but nothing
0
I am wondering what exactly am I missing here? I've been worked up about this overnight and I feel the solution is so simple but I'm missing the point.
My main problem seems to be the error message that prints out throughout my other trials concerning an "invalid conversion from 'char*' to 'char'. Further, other functions in the program not shown require the letters of each word in the elements of the String class array to be manipulated (preferable as a string class array instead of C-string). I'm at a lost here. Please help?
I found this helpful link but it's for Java. What would be an equivalent for C++?
http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/09/String-array.html
A couple places to start:
You're trying to use wordList, which is of type string, like it's an array of strings. wordList[5] will give you the sixth character in wordList... assuming you've assigned it correctly.
SIZE appears to be undefined.