I created a program that the user enters a string. But i need to count how many letters are in the string. The problem is im not allowed to use the strlen()function. So i found some methods but they use pointers but im not allowed to use that yet as we havent learned it. Whats the best way to do this in a simple method? I also tried chars but i dont have luck with that either.
#include <iostream>
using namespace std;
string long;
string short;
int main()
{
cout << "Enter long string";
cin >> long;
cout << "Enter short string";
cin >> short;
return 0;
}
I need to get the length of long and short and print it.
I am trying to use it without doing strlen as asked in some previous questions.
Do you mean something like this?
//random string given
int length = 1;
while(some_string[length - 1] != '\0')
length++;
Or if you don't want to count the \0 character:
int length = 0;
while(some_string[length] != '\0')
length++;
You can count from the beginning and see until you reach the end character \0.
std::string foo = "hello";
int length = 0;
while (foo[++length] != '\0');
std::cout << length;
If you use standard cpp string object I think the best way to get length of your string is to use method:
long.size();
It gives you number of characters in string without end string character '\0'. To use it you must include string library :
#include <string>
If you decide to use char table you can try method from cin:
char long_[20];
cout << "Enter long string\n";
int l = cin.getline(long_,20).gcount();
cout << l << endl;
gcount()
Related
#include <iostream>
#include <string>
using namespace std;
static char sentence[100];
void sameletter(char sentence[100])
{
int meter=0;
char letter;
cout<<"Enter the letter you want to find in this sentence : ";
cin>>letter;
for(int i=0; sentence[i] != '\0'; i++)
{
if(sentence[i]==letter)
{
meter++;
}
}
cout<<letter<<" letter used "<<meter<<" time(s)."<<endl;
}
int main()
{
cout<<"Enter Sentence : ";
cin>>sentence[100];
gets(sentence);
sameletter(sentence);
}
This is code i wrote. But for some reason it never includes the first letter to the end result. For example lets say i write "We love stack overflow" and i wanted how many times this sentence has the letter "w" so i hit w and it only shows : "w letter used 1 many time(s)." instead of 2. other letters like "o" works perfectly so it's only a problem about the first letter :/ can someone help me about it ?
Thanks !
This line:
cin >> sentence[100];
will read a single character into the 100th index of sentence, which invokes underfined behavior.
Also, gets has been removed from c++, and you should no longer use it.
Instead, you should use getline:
int main()
{
std::cout<<"Enter Sentence : ";
std::getline(std::cin, sentence);
sameletter(sentence);
}
Also, avoid using namespace std;, it's bad practice.
There's no reason for sentence to be static, or global.
Also, you could just use std::string, instead of char arrays. It will make your life easier. e.g. your loop could be replaced by an algorithm:
int meter = std::count_if(sentence.begin(), sentence.end(),
[=] (unsigned char c) {
return std::tolower(c) == std::tolower(letter);
});
I am trying to write a function in a program that will take a string, a word and an integer and use the int as the index value and the word as the replacement value. For example, if the string is "This is a test.", the word is "example", and the number is 4, then the result would be "This is an example". This is what I have so far (I had to make multiple copies of the string because eventually, I am going to be passing it into two other functions by reference instead of as value)Right now it is using the character index instead of the word index in order to replace. How do I fix that?
#include "pch.h"
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string Input = "";
string Word = "";
int Number = 0;
cout << "Pleas enter a string using only lower case letters. \n";
getline(cin, Input);
cout << "Please enter a word using only lower case lettersS. \n";
getline(cin, Word);
cout << "Please enter a number. \n";
cin >> Number;
string StringCopy1 = Input;
string StringCopy2 = Input;
string StringCopy3 = Input;
}
void stringFunctionValue(string StringCopy1, int Number, string Word)
{
StringCopy1.replace(Number, Word.length, Word);
return StringCopy1;
}
First thing you have to do is find the nth word.
The first thing to come to mind is using std::istringstream to pull the string apart with >> and a std::ostringstream to write the new string.
std::istringstream in(StringCopy1);
std::string token;
std::ostringstream out;
int count = 0;
while (in >> token) // while we can get more tokens
{
if (++count != number) // not the number of the token to replace
{
out << token << " "; // write the token
}
else
{
out << word << " "; // write the replacement word
}
}
return out.str();
While this is easy to write, it has two problems: It loses the correct type of whitespace in the string AND places an extra space on the end of the string. It's also kind of slow and uses a lot more memory than if you modify the string in place.
Use std::string::find_first_not_of to find the first non-whitespace character. This will be the start of the first word. Then use std::string::find_first_of to find the next whitespace character. This will be the end of the word. Alternate back and forth finding non-whitespace then whitespace until you find the beginning and ending of the nth word. std::string::replace that word. This approach requires you to write more and more complicated code, but is much more satisfying. This is why I outlined it rather than fully implementing it: To allow you the joy for yourself.
Note: void stringFunctionValue(string StringCopy1, int Number, string Word) gives you no way to provide the result back to the user. This makes for an unhelpful function. Consider returning a string rather than void.
I am a beginner in c++ and I want to enter a string as character by character into an array , so that I can implement a reverse function .. However unlike C when the enter is hit a '\n' is not insterted in the stream.. how can I stop data from being entered ?
my code is :
#include<iostream>
#include<array>
#define SIZE 100
using namespace std;
char *reverse(char *s)
{
array<char, SIZE>b;
int c=0;
for(int i =(SIZE-1);i>=0;i--){
b[i] = s[c];
c++;
}
return s;
}
int main()
{
cout<<"Please insert a string"<<endl;
char a[SIZE];
int i=0;
do{
cin>>a[i];
i++;
}while(a[i-1]!= '\0');
reverse(a);
return 0;
}
When you read character by character, it really reads characters, and newline is considered a white-space character.
Also the array will never be terminated as a C-style string, that's not how reading characters work. That means your loop condition is wrong.
To begin with I suggest you start using std::string for your strings. You can still read character by character. To continue you need to actually check what characters you read, and end reading once you read a newline.
Lastly, your reverse function does not work. First of all the loop itself is wrong, secondly you return the pointer to the original string, not the "reversed" array.
To help you with the reading it could be done something like
std::string str;
while (true)
{
char ch;
std::cin >> ch;
if (ch == '\n')
{
break; // End loop
}
str += ch; // Append character to string
}
Do note that not much of this is really needed as shown in the answer by Stack Danny. Even my code above could be simplified while still reading one character at a time.
Since you tagged your question as C++ (and not C) why not actually solve it with the modern C++ headers (that do exactly what you want, are tested, save and work really fast (rather than own functions))?
#include <string>
#include <algorithm>
#include <iostream>
int main(){
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
output:
Enter a string: Hello Test 4321
1234 tseT olleH
This is a part of the program which I am required to make in Turbo C++;
Here, if I give input of id as "PLAYNOW" and pass as "PASSWORD", variable p is storing the value 0 but i isn't storing. id variable is storing some junk number at the end of PLAYNOW and I am not able to figure out why. Please help. Please ignore any header files not added and the way I have taken input of password.
Thank you!
#include<conio.h>
#include<iostream.h>
#include<string.h>
#include<process.h>
int main()
{
char id[7],pass[8];
cout<<"Enter id: ";
cin.getline(id,7);
cout<<"Enter pass: ";
cin.getline(pass);
char idc={"PLAYNOW"};
char passc={"PASSWORD"};
int i=strcmp(id,idc);
int p=strcmp(pass,passc);
if(i==0&&p==o)
cout<<"Welcome. ";
else
exit(0);
getch();
return 0;
}
One problem in OP's code is the insufficient amount of memory allocated for the variables. For example, with those lines:
char id[7];
cin.getline(id,7);
The function getline can read and store from the input stream up to 6 chars in the null terminated char array id, but then the program has to compare that string to PLAYNOW, which is 7 chars long.
This leads to next problem, when getline leaves unread chars in the stream, the failbit is set, preventing any further readings.
To fix those, even with the old standard, OP can do something like this:
const int ssize = 32; // enough space to store id or password
const int ssmax = 1024;
// big value... ^^ try std::numeric_limits<std::streamsize>::max() instead
char id[ssize],
pass[ssize];
cout << "Enter id: ";
cin.getline(id, ssize); // extract (ssize - 1) chars from input
if ( cin.fail() ) {
cin.clear(); // if user entered more then ssize chars
cin.ignore(ssmax, '\n'); // clear the stream
}
The same for pass (OP didn't pass 8 to the second getline, too).
Then, the declarations of the strings which contain the expected ID and password are wrong. Use those:
char idc[] = "PLAYNOW";
char passc[] = "PASSWORD";
The last lines could be rewritten too:
if ( strcmp(id, idc) != 0 || strcmp(pass, passc) != 0 )
exit(0);
cout << "Welcome. ";
cin.get();
return 0; // end of main()
BTW, I'm quite sure that std::strings belonged to C++98, so this should work too:
#include <iostream>
#include <string>
int main() {
std::string id, pass;
std::cout << "Enter id: ";
std::getline(std::cin, id);
std::cout << "Enter pass: ";
std::getline(std::cin, pass);
std::string idc("PLAYNOW");
std::string passc("PASSWORD");
if ( idc != id || passc != pass )
exit(0);
std::cout << "Welcome. ";
return 0;
}
if id and pass are "PLAYNOW" and "PASSWORD", id has length is 8 , and pass has length is 9 (NULL character at end of string).
I changed as below and result print in cmd is Welcome.
char id[8],pass[9];
...
cin.getline(id,8);
char idc[] = "PLAYNOW" ;
char passc[] = "PASSWORD" ;
...
cin.getline(pass,9);
...
if(i==0&&p==0)
Well, beyond numerous mistakes that I simply can't begin to list, I see that you are reading from a char stream without giving the stream size. Try:
cin.getline(pass, 8);
I would seriously consider using a compiler that is a bit newer, and focusing more on readability and convention, as it's clear that there are better ways to do what is ultimately being done here. Especially with the line I pointed out, this is very ad hoc. What if the string is longer/shorter than 8 characters?
I'm trying to remove all punctuation characters from a std::string in C++. My current code:
string str_in;
string::size_type i, j;
cout << "please input string with punctuation character..." << endl;
cin >> str_in;
for (i = 0, j = 0; i != str_in.size(); ++i)
if (!ispunct(str_in[i]))
str_in[j++] = str_in[i];
str_in[j] = '\0';
cout << str_in << endl;
Is str_in[j] = '\0'; wrong?
If you want to truncate str_in to the first j characters, you can say str_in.resize(j).
If you want to use the standard library you could apply the erase-remove idiom like this:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string str_in;
std::getline(std::cin, str_in);
// Here is where the magic happens...
str_in.erase(std::remove_if(str_in.begin(), str_in.end(), ::ispunct), str_in.end());
std::cout << str_in << '\n';
return 0;
}
the C++ string type is NOT implemented to be null terminated (although a c_str() call will give you a null terminated string.)
So yes, str_in[j] = '\0' is wrong for at least two reasons:
The str_in.length() will not reflect the size of the string you expect with the punctuation removed.
The null charatcter is an extra charter which will be sent to any output stream,such as cout << str_in;
Using the std::string class you should probably not oveeride the same buffer, but probably use a str_out buffer instead which will have the right length after you copy all the wanted (i.e. excluding the punctuation character), OR you should instead adjust the length of the str_in instead of adding the null.
I think str_in[j] = '\0' is wrong when the string has no any punctuation.
Instead of modifying the same string, create a new string (e.g. str_out) and append to that:
str_out += str_in[i];