C++ string only letters [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've got something like this. The problem is strings must be letters only, how can I do this? I've been sitting over this for few hours now and can't find any working solution. I've tried to use answers from this topic Accept only letters but I guess I'm too dumb and still can't make it work :(
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(void)
{
vector <string> strings;
string line;
do
{
cout << "enter string, 'stop' stops: ";
cin >> line;
strings.push_back(line);
}
while (line != "stop");
vector <string> :: iterator w;
cout << "Before sorting \n";
for (w=strings.begin(); w!=strings.end(); w++)
cout << *w << endl;
sort (strings.begin(),strings.end());
cout << "After sorting \n";
for (w=strings.begin(); w!=strings.end(); w++)
cout << *w << endl;
}

You need to add validation code. For simple cases, you can do
something like:
if ( std::find_if( line.begin(),
line.end(),
[]( unsigned char ch ) { return !isalpha( ch ); }
) != line.end() ) {
// not all letters
}
(This is really only appropriate for school projects, and won't
work for the usual network encoding, UTF-8.)

Related

How to count a certain character within a file C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
int main()
inFile.get(file);
while(inFile) {
inFile.get(file);
cout << file;
if(inFile.fail()) {
break;
}
if(inFile) {
++charNum;
}
if(inFile && c =='<') {
++comNum;
}
The values keep outputting 1, and its not actually counting the amount of < in the file. If I put inFile >> c, it makes my file a bunch of gibberish. What is the best way to count a certain amount of characters within a file, that is being opened by the user? Thank you.
You can rely on algorithms provided by the Standard Library.
#include <algorithm>
#include <fstream>
#include <iostream>
int main(int argc, char* argv[]) {
std::ifstream fp(argv[1]);
const auto count = std::count(std::istreambuf_iterator<char>{fp},
std::istreambuf_iterator<char>{}, '<');
std::cout << "count: " << count << "\n";
}

Changing first and last letter of a 6 letter word in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is there any other method to change the first letter and last letter of a 6 letter word?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word;
cout<< "\nEnter a 6 letter word or numbers: ";
cin>>word;
word[0]++;
word[5]++;
cout << "Result: " << word << endl;
return 0;
}
you could also use string::replace but it is a pretty roundabout way compared to replacing using the subscript operator.
something like
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word;
cout<< "\nEnter a 6 letter word or numbers: ";
cin>>word;
cout<<word;
string repl = "x";
word.replace(5,1, repl); //replace the 5th position with 1
//character using string repl
cout << "Result: " << word << endl;
return 0;
}
Take a look at http://cplusplus.com/reference/string/string/replace/
C++, best way to change a string at a particular index
How to replace one char by another using std::string in C++?

Can't erase digits from c++ string by using the 'erase' function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Using c++ 14.
I'm prompting the user for a string containing both letters and integers, and trying to "strip" the integers from the string itself via the string.erase() function.
The problem i'm facing is when there are 2 or more sequential numbers, than the function seems to erase the first but delete the latter.
Example:
input: H23ey Th2e3re St01ack O34verflow
output: H3ey There St1ack O4verflow
I can do it another way by using a new string, looping through the existing one and adding only what isalpha or isspace, but it seems messier.
code:
string digalpha {};
cout << "Enter string containing both numbers and letters: ";
getline(cin, digalpha);
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1);
cout << digalpha << endl;
cout << endl;
return 0;
In the first sentence you were writing that you are using C++14.
In "more modern" C++ the usage of algorithm is recommended. So normally you would not use C-Style For loops.
The standard approach that you can find everywhere, is a combination of erase with std::remove_it. You will find this construct in many many examples.
Please consider to use such a solution instead of a for loop.
You can even include the output in an algorithm using std::copy_if.
Please see:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::string test1{ "H23ey Th2e3re St01ack O34verflow" };
std::string test2{ test1 };
// C++ standard solution for erasing stuff from a container
test1.erase(std::remove_if(test1.begin(), test1.end(), ::isdigit), test1.end());
std::cout << test1 << "\n\n";
// All in one alternative
std::copy_if(test2.begin(), test2.end(), std::ostream_iterator<char>(std::cout), [](const char c) { return 0 == std::isdigit(c); });
return 0;
}
If there's two digits next to each other, it skips the second digit. This happens because the index, i, keeps going up, even though everything got shifted over:
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1); //Here, i goes up anyway, skipping character after digit
To fix this, we just have to decriment i after erasing a digit:
for (size_t i {}; i < digalpha.size(); i++) {
if (isdigit(digalpha.at(i))) {
digalpha.erase(i,1);
i--;
}
}

How to convert first letter to uppercase in c++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a Structure
struct StudentRecord{
char StudentFamilyName[20]
}gRecs[50];
cout << "Family Name: ";
cin >> gRecs[50].StudentFamilyName;
char str[20];
str[20] = toupper(gRecs[i].StudentFamilyName[0]);
cout << str;
What i want to do is to store the first letter of family name as
upper case and the rest as lower case? How do I do that?
I used toupper but when I implement it doesnot work. Could anyone help me out? Thank you.
Note: This was an exam question.
Here's how to capitalize a string using character arithmetic:
#include <iostream>
#include <string>
using namespace std;
string ToCapitalize(string input)
{
if (input.length() > 1 && input[0] >= 'a' && input[0] <= 'z')
{
input[0] -= 32;
}
return input;
}
int main() {
std::string StudentFamilyName("smith");
cout << StudentFamilyName << std::endl;
cout << "Capitalized: " << ToCapitalize(StudentFamilyName) << endl;
}
Your problem isn't with toupper. There are a couple of them, actually.
cin >> gRecs[50]
gRecs is size 50, so index 50 is out of bounds. To insert into the first record you would use
cin >> gRecs[0].StudentFamilyName;
Second record: gRecs[1], etc.
Next,
char str[20];
str[20] = toupper(str[0]);
You declare str in which nothing is populated, and then call toupper on it.
And the index ([20]) is the 21st character (which is out of bounds). You are attempting to convert the 21st character in the str toupper.
What you need is something like:
// i is the index into your student records array, possibly in a loop
cin >> gRecs[i].StudentFamilyName;
gRecs[i].StudentFamilyName[0] = toupper(gRecs[i].StudentFamilyName[0]);

My C++ program not working properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have to make a program in C++ that will read numbers and then arrange them in ascending order. The numbers can be infinite, so the program should read numbers until any particular value is entered to terminate the reading process. I have written below code but is not working and showing undesired output. I will be so thankful if someone will help me.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p,*q,i=1,j,k,temp;
p=(int*)malloc(sizeof(int));
cin>>*p;
while((*p)!=-1) //read until -1 is entered
{
i++;
p=(int*)realloc(p,sizeof(int)*i);
q=p;
p=p+(i-1); //going to next address to read
cin>>*p;
}
p=q;
for(j=1;j<i;++j)
{
for(k=0;k<i-j-1;++k)
{
if((*(p+k))>(*(p+k+1)))
{
temp=*(p+k);
*(p+k)=*(p+k+1);
*(p+k+1)=temp;
}
}
}
cout<<"\n";
for(j=0;j<i-1;++j)
{
cout<<*(p+j)<<" ";
}
}
Expanding on my comment, here is what an actual C++ solution might look like:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers;
int number = -1;
std::cin >> number;
while (number != -1)
{
numbers.push_back(number);
number = -1;
std::cin >> number;
}
std::sort(numbers.begin(), numbers.end());
for (int x : numbers)
{
std::cout << x << ' ';
}
std::cout << '\n';
}
After
p=p+(i-1);
p is no longer a pointer that is valid to realloc.
Replace
p=p+(i-1);
cin>>*p;
with
cin >> p[i-1];
and get rid of q.
(You can use cin >> *(p + i - 1); if you insist on obfuscation.)
Your sorting routine also becomes much more readable if you replace the pointer arithmetic with indexing.