Indexing an array of chars - issue with pointers - c++

#include <iostream>
#include <cstring>
using namespace std;
void getInput(char *password, int length)
{
cout << "Enter password: ";
cin >> *password;
}
int countCharacters(char* password)
{
int index = 0;
while (password[index] != "\0")
{
index++;
}
return index;
}
int main()
{
char password[];
getInput(password,7);
cout << password;
return 0;
}
Hi!
I'm trying two things here which I'm unable to do atm. I'm trying to create a char array with unspecified length in main, and I'm trying to count the number of words in the char array in the function countCharacters. But password[index] doesnt work.
EDIT: I'm doing a homework assignment, so I have to use cstrings only.
EDIT2: And I'm not allowed to use the "strlen"-function either.

At first replace
char password[];
by
char password[1000]; // Replace 1000 by any maximum limit you want
And then replace:
cin >> *password;
by
cin >> password;
Also instead of "\0" you should put '\0'
P.S. There is no char array with unspecified length in C++, you should use std::string instead(http://www.cplusplus.com/reference/string/string/):
#include <string>
int main() {
std::string password;
cin >> password;
cout << password;
return 0;
}

Related

Can you use "cin" with string?

I was taught that you have to use gets(str) to input a string and not cin. However I can use cin just fine in the program below. Can someone tell me if you can use cin or not. Sorry for my bad English. The program lets you insert 5 names and then print those names to the screen.
Here's the code:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char **p = new char *[5];
for (int i = 0; i < 5; i++)
{
*(p + i) = new char[255];
} //make a 2 dimensional array of strings
for (int i = 0; i < n; i++)
{
char n[255] = "";
cout << "insert names: ";
cin >> n; //how i can use cin here to insert the string to an array??
strcpy(p[i], n);
}
for (int i = 0; i < n; i++)
{
cout << p[i] << endl; //print the names
}
}
You can indeed use something like
std::string name;
std::cin >> name;
but the reading from the stream will stop on the first white space, so a name of the form "Bathsheba Everdene" will stop just after "Bathsheba".
An alternative is
std::string name;
std::getline(std::cin, name);
which will read the whole line.
This has advantages over using a char[] buffer, as you don't need to worry about the size of the buffer, and the std::string will take care of all the memory management for you.
Use ws (whitespace) in getline() like getline(cin>>ws, name);
If numeric input is before the string then due to whitespace the first string input will be ignored. Therefore use ws like getline(cin>>ws, name);
#include <iostream>
using namespace std;
main(){
int id=0;
string name, address;
cout <<"Id? "; cin>>id;
cout <<"Name? ";
getline(cin>>ws, name);
cout <<"Address? ";
getline(cin>>ws, address);
cout <<"\nName: " <<name <<"\nAddress: " <<address;
}

Why is cin operation undefined?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main()
{
bool string1[20];
cout << "Enter string: ";
cin >> string1;
int counter = 0;
int length;
length = strlen(string1);
This is incomplete code, but my question is why am I getting a compiling error when using cin? It says:
error: no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘bool [20]’)
On this line:
cin >> string1;
I'm not sure how to fix this.
bool string1[20]; is the wrong choice for the user input as a string, all it does is create an array of 20booleans, true or false which is not what you want.
what you are after is your included #include <string>
string string1;
cout << "Enter string: ";
cin >> string1;
Instead of using strlen you get the length by using the length method provided by std::string
auto length = string1.length()
There is no operator>> for reading an array of bool values. What you need is an array of char values instead:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
char string1[20];
cout << "Enter string: ";
cin >> setw(20) >> string1;
int length = strlen(string1);
Or better, a single std::string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string string1;
cout << "Enter string: ";
cin >> string1;
int length = string1.length();
I think you are confusing string with array. string1 in your code is not an string its an array. So, you can't just put data in it without giving the proper index number. Also remember its an bool type so you can only enter 0/1/true/false value.
Again, you have used strlen() function in your code which is used for determining the length of the string but your is an array. You didn't ask about this but when I ran the code in my IDE it got error.
Here is one way to do it :
main()
{
bool string1[20];
cout << "Enter string: ";
for(int i=0;i<20;i++)//iterating through the boolian array
{
cin >> string1[i];
}
int counter = 0;
int length;
length = sizeof(string1)/sizeof(string1[0]);
cout<<length;//printing the size of the array
}

c++ - cin word to char array, each input word display all words.

1.
Create global char array name inputData and size 100- input word
create dynamic array which had size = input word;
2.
add dynamic array which stock pointers to all words.input new word effect show all words. if array is too small, double array size.
So I now how do first array , create array and input in loop, but I don't now how add word to array instead overwrite and then show all words. Any help?
Maybe I just do not understand this task.
#include <iostream>;
#include <string.h>;
#include <stdio.h>
char *inputData= new char[100];
using namespace std;
int main(){
// cin>>::inputData;
//char* tablica2= new char (strlen(inputData));
cout<<"how many words"<<endl;
int input;
cin>>input;
int temp=0;
int len=0;
char *tab1= new char[input];
for(int i=0;i<input;i++){
cout<<" enter word "<<i+1<<endl;
char* tem2= new char[20];
cin>>::inputData;
len=len+strlen(::inputData);
cout<<len;
// int temp= temp+ strlen(::inputData);
//cout<<::inputData[temp];
// *(inputData+i)=*tem;
}
I am not sure that I have understand what you want to do, but maybe you could use the ostrstream class to solve a part of your problem:
#include <iostream.h>
#include <strstream.h>
using namespace std;
main(){
char buf[100];
ostrstream out(buf,sizeof(buf)) //opens output array,like cout but,
//writes the data to the array.
out << "Write text that will be written into buf\n";
out << "This will be attached";
out << ends; //ensures that buf is null-terminated
cout << buf;
return (0);
}
Hope that helps.
If you want to get a user-input with white-spaces you could use this code:
#include <string.h>
#include <iostream>
using namespace std;
int main(void) {
string name;
getline(cin, name);
cout << name << endl;
return (0x0);
}
And if you like to copy the data into an old cstring:
char* old_cstr;
old_cstr = new char[name.length() + 1];
strcpy(old_cstr, name.c_str());
cout << old_cstr << endl;
Ok I do this and all work. (first loop clear inputData- delete look like don't work)
int main(){
for(int i=0;i<99;i++){
::inputData[i]='\0';
}
//cin<<::inputData;
//char* tablica2= new char (strlen(inputData));
cout<<"how many words"<<endl;
int input;
cin>>input;
int temp=0;
int len=0;
char *tab1= new char[input];
for(int i=0;i<input;i++){
cout<<" enter word "<<i+1<<endl;
char* tem2= new char[20];
cin>> tem2;
strcat(::inputData,tem2);
tab1[i]=*tem2;
cout<<::inputData;
len= len+ strlen(tem2);
cout<<len;
// if(len>strlen(::inputData)){
// ::inputData= new char[(strlen(::inputData)*2)];
// }
}
}

string subscript out of range c++

I need a help in a very basic c++ code.
My program is about guessing name game the problem which i faced is in reading string char by char
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void Play(int, int,int, string[], string[]);
string GetRandomName(int, int, int , string[], string[]);
const int ArrayMax = 100;
void Play(int selection, int FArraySize, int MArraySize,string Female[], string Male[])
{
int MAX_TRIES = 3;
int i=0;
ofstream ofFile;
ifstream InFile;
int num_of_wrong_guesses=0;
char letter;
string GuessedName;
GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);
cout << "Guess the following name:" << endl;
while (GuessedName[i]!= 0 ){
cout<<"?";
i++;
}
cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
cin >> letter;
return;
}
I don't complete coding...
the problem is in the while loop how can i solve it without using cstring?
could you help me?
int i = 0;
while(GuessedName[i] != 0)
{
cout << "?";
i++;
}
Seems like you are trying to print sequence of ? with the length of the string to guess. But you cannot treat std::string as c-string. When its length is n, GuessedName[n] is string subscript out of range - you cannot access one element past end - it's not null-terminated. Use for loop:
for(int i = 0; i < GuessedName.length(); ++i)
cout << "?";
Or simply:
cout << std::string(GuessedName.length(), '?');
Change the while loop like this:
while (GuessedName[i]){
cout<<"?";
i++;
}

reverse of the string using recursion

Hey guys i get stuck in the unusual situation. This is my code, it works perfectly for returning the reverse of the string but it gives output with including the space so I don't want that space to be included in my programme output so anyone has suggestions about this plz share it... by the way this is my code :
#include <iostream>
using namespace std;
string reverse(string str, int size) {
if (size == -1)
return "";
else
{
char a;
a = str[size];
return a + reverse(str, size - 1);
}
}
int main() {
int size;
cout << "the size of the string : ";
cin >> size;
string str;
cout << "enter the word : ";
cin >> str;
cout << reverse(str, size);
}
Since you use std::string, you don't need to specify the size of the string, but use the std::string::size() or std::string::length() member functions. Also, a = str[size]; is problematic when size equals to the size of the string, since you perform an out of bound access (remember that C++ uses zero-based indexing). You can simplify the code a lot, ending up with
#include <iostream>
#include <cstddef> // for std::size_t
using namespace std;
string reverse(string str, std::size_t pos) {
return (pos == 0 ? "" : str[pos - 1] + reverse(str, pos - 1));
}
int main() {
string str;
cout << "enter the word : ";
getline(cin, str); // allow for spaces in the string
cout << reverse(str, str.size()) << endl;
}
Here, instead of using cin >> str, I used getline(cin, str), since cin reads up to the first whitespace, whereas getline allows to read strings that containg spaces.
Change the implementation of the function reverse to the following.
string reverse(string str ,int size){
if (size==-1)
return "";
else
{
char a;
a=str[size];
if (' ' == a )
return reverse(str,size-1)
else
return a+reverse(str,size-1);
}
}
Alternatively, do some pre-processing on th input.