How compare char str[MAXCHAR] with a string? - c++

I want compare if both sequence are equals and i'm using the following code but comparation always return false.
=========================================================================
// testecompare.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
string getCurrentDirectoryOnWindows()
{
const unsigned long maxDir = 260;
char currentDir[maxDir];
GetCurrentDirectory(maxDir, currentDir);
strcat(currentDir, "\\l0gs.txt");
return string(currentDir);
}
string ReadFileContent() {
string STRING;
string aux;
ifstream infile;
infile.open(getCurrentDirectoryOnWindows());
while (!infile.eof())
{
getline(infile, STRING);
return STRING;
}
infile.close();
return "";
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[MAXCHAR] = "";
sprintf(str, "0x0%X", "1D203E5");
cout << str << endl;
cout << "File content: " << ReadFileContent() << endl;
// if i have the string "0x01D203E5" in my txt file
if (_stricmp(str,ReadFileContent().c_str()) == 0) {
cout << "Contents are equals!\n";
}
system("pause");
return 0;
}
How make this comparation correctly?
Thank you very much.

An easy trick for comparing instances of different types is to convert them to a common type then compare.
So for example:
std::string content(ReadFileContent());
std::string from_array(str)
if (from_array == content)
{
}
Edit 1: Working example
The code works.
Here is a working program:
#include <iostream>
#include <string>
int main()
{
static const char text[] = "Hello";
std::string text_as_string(text);
std::string expected_str("Hello");
if (text_as_string == expected_str)
{
std::cout << "Strings are equal: " << text_as_string << "\n";
}
else
{
std::cout << "Strings are not equal.\n";
}
return 0;
}
$ g++ -o main.exe main.cpp
$ ./main.exe
Strings are equal: Hello
Remember, the above code samples are compare entire or whole strings, not substrings. If you want to search for a key string within a larger string, that requires different functions.

Related

How do I search a string from a file and return the line location using functions in C++?

I am trying to make a program that lets me search for groups of words in a file and then it would return the line locations where they are found. I made it work for a little bit but for some reason, the value of int FileLine (line location) keeps on stacking up whenever a new word search is introduced.
include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
string S1, S2, S, Line;
int FileLine = 0;
int CountInFile(string S) {
ifstream in("DataFile.txt");
while (getline(in, Line)) {
FileLine++;
if (Line.find(S, 0) != string::npos) {
cout << "Found " << S << " at line " << FileLine << "\n";
}
}
return 0;
in.close();
}
int main()
{
// Words to search
CountInFile("Computer Science");
CountInFile("Programming");
CountInFile("C++");
CountInFile("COSC");
CountInFile("computer");
This is the output:
Is there a way that I can stop the FileLine value from stacking?

Lowercasing Capital Letters in char array[] in C++ through Pointers

I am trying to use pointers to recursively lowercase all capital letters
using the C++ programming language. Below is the code snippet:
// Example program
#include <iostream>
#include <string>
using namespace std;
void all_lower(char* input) {
if ( *input ) {
cout << input << endl;
return;
}
if ( *input >= 'A' && *input <= 'Z') {
*input += 32; // convert capital letter to lowercase
}
cout << *input << endl;
all_lower(++input); // simply move to next char in array
}
int main() {
char test[] = "Test";
all_lower(test);
return 0;
}
The output ends up being:
"Test"
even though I tried to increase the ASCII code value of the element by 32.
You are exiting the function on the first non-null character detected, which is 'T', and then you output the entire array before exiting, so you are seeing the original unmodified input. You are not recursing through the array at all. You need to recurse through the array until you reach the null terminator.
You need to change this:
if ( *input ) {
cout << input << endl;
return;
}
To this instead:
if ( *input == 0 ) {
return;
}
Then the function will work as expected.
That being said, I suggest you remove the cout statements from the function, and do a single cout in main() after the function has exited. This will speed up the function, and prove that the content of the test[] array is actually being modified:
#include <iostream>
using namespace std;
void all_lower(char* input)
{
if ( *input == 0 ) {
return;
}
if ( *input >= 'A' && *input <= 'Z') {
*input += 32; // convert capital letter to lowercase
}
all_lower(++input); // simply move to next char in array
}
int main()
{
char test[] = "TEST";
cout << "Before: " << test << endl;
all_lower(test);
cout << "After: " << test << endl;
return 0;
}
Live Demo
And, since you are using C++, consider removing all_lower() altogether and use the STL std::transform() algorithm instead:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char test[] = "TEST";
cout << "Before: " << test << endl;
transform(test, test+4, test, [](char ch){ return tolower(ch); });
cout << "After: " << test << endl;
return 0;
}
Live Demo
Something short and easy:
#include <iostream>
#include <string>
using namespace std;
void all_lower(const char* input) {
if (!*input) {
std::cout << std::endl;
return;
}
std::cout << (char)(std::isalpha(*input) ? tolower(*input) : *input);
all_lower(++input); // simply move to next char in array
}
int main() {
all_lower("Test");
return 0;
}

C++ Check that in a string only exist following characters

The valid charaters are
// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/
#include <iostream>
#include <string>
using namespace std;
int main();
{
bool bIsValid = true;
// test characters
string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
string s("foo#?+baa") ; // should bring a "false" because of the "#?+" characters
string::const_iterator it = strCheck.begin();
// this is NOT a clever soulution has anybody a better idea ?
while (s.find(*it) != string::npos)
{
++it;
if(!s.find((*it))
{
bIsValidKey = false;
break;
}
}
cout << "Is Valid: " << bIsValid << endl ;
}
My problem is how can a get the first charater after the iteratorpoint to compare
with the allowed charactes. I need something like (*it).first_charater_after to
solve the problem.
Dos anybody has an other idea to check that in the string only exists a defined
number of charaters?
Use string::find_first_not_of?
Try this:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
bool bIsValid = true;
string s("GHHbaa111__") ; // Add/remove other characters
regex r("^[[:alnum:]_]*$");
if (regex_match(s,r)) {
cout << "Valid string" << endl;
} else {
cout << "Invalid string" << endl;
}
}
#include <iostream>
#include <string>
int main() {
bool bIsValid = true;
// test characters
std::string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
std::string s("foo#?+baa") ; // should bring a "false" because of the "#?+" characters
if (s.find_first_not_of(strCheck) != std::string::npos)
bIsValid = false;
std::cout << "Is Valid: " << bIsValid << std::endl ;
}

getting a sub string of a std::wstring

How can I get a substring of a std::wstring which includes some non-ASCII characters?
The following code does not output anything:
(The text is an Arabic word contains 4 characters where each character has two bytes, plus the word "Hello")
#include <iostream>
#include <string>
using namespace std;
int main()
{
wstring s = L"سلام hello";
wcout << s.substr(0,3) << endl;
wcout << s.substr(4,5) << endl;
return 0;
}
This should work: live on Coliru
#include <iostream>
#include <string>
#include <boost/regex/pending/unicode_iterator.hpp>
using namespace std;
template <typename C>
std::string to_utf8(C const& in)
{
std::string result;
auto out = std::back_inserter(result);
auto utf8out = boost::utf8_output_iterator<decltype(out)>(out);
std::copy(begin(in), end(in), utf8out);
return result;
}
int main()
{
wstring s = L"سلام hello";
auto first = s.substr(0,3);
auto second = s.substr(4,5);
cout << to_utf8(first) << endl;
cout << to_utf8(second) << endl;
}
Prints
سلا
hell
Frankly though, I think your substring calls are making weird assumptions. Let me suggest a fix for that in a minute:

convert string to integer in c++

Hello
I know it was asked many times but I hadn't found answer to my specific question.
I want to convert only string that contains only decimal numbers:
For example 256 is OK but 256a is not.
Could it be done without checking the string?
Thanks
The simplest way that makes error checking optional that I can think of is this:
char *endptr;
int x = strtol(str, &endptr, 0);
int error = (*endptr != '\0');
In C++ way, use stringstream:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream sstr;
int a = -1;
sstr << 256 << 'a';
sstr >> a;
if (sstr.failbit)
{
cout << "Either no character was extracted, or the character can't represent a proper value." << endl;
}
if (sstr.badbit)
{
cout << "Error on stream.\n";
}
cout << "Extracted number " << a << endl;
return 0;
}
An other way using c++ style : We check the number of digits to know if the string was valid or not :
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
int main(int argc,char* argv[]) {
std::string a("256");
std::istringstream buffer(a);
int number;
buffer >> number; // OK conversion is done !
// Let's now check if the string was valid !
// Quick way to compute number of digits
size_t num_of_digits = (size_t)floor( log10( abs( number ) ) ) + 1;
if (num_of_digits!=a.length()) {
std::cout << "Not a valid string !" << std::endl;
}
else {
std::cout << "Valid conversion to " << number << std::endl;
}
}