Tag Archives: c++

CIN in C + + cin.get ()、 cin.getline (), getline(), gets() function

When learning C++, these input functions are a little confusing; Here’s a summary:
Cin
2 cin. Get ()
3 cin. Getline ()
4 getline()
5 gets()
6 getchar()
Add: cin. Ignore (); Cin. Get ()// skips a character, such as unwanted carriage return, space, etc
1, cin> >          
Usage 1: The most basic and commonly used usage is to enter a number:
#include < iostream>
using namespace std;
main ()
{
int a,b;
cin> > a> > b;
cout< < a+b< < endl;
}
Input: 2[enter]3[enter]
output: 5
Note: & gt; > Is to filter out invisible characters (such as space return, TAB, etc.)
cin> > noskipws> > input[j]; // If you don’t want to skip white space characters, use noskipWS flow control
Usage 2: Accept a string and end with “space”, “TAB”, or “enter”
#include < iostream>
using namespace std;
main ()
{
char a[20];
cin> > a;
cout< < a< < endl;
}
Input: JKLJKLJKL
output: JKLJKLJKL
Input: JKLJKL // end of blank
output: JKLJKL
2, cin. The get ()
Usage 1: Cin. Get (character variable name) can be used to receive characters
#include < iostream>
using namespace std;
main ()
{
char;
ch = cin. The get ();// or cin. Get (ch);
cout< < ch< < endl;
}
Input: JLJKLJKL
output: j
Usage 2: Cin. Get (character array name, number of characters to receive) is used to receive a line of strings and can receive Spaces
#include < iostream>
using namespace std;
main ()
{
char a[20];
cin. Get (a, 20);
cout< < a< < endl;
}
JKL JKL
output: JKL JKL JKL
Input: abcdeabcdeabcdeabcdeabcde 25 characters (input)
output: abcdeabcdeabcdeabcd receive (19 + 1 character ‘\ 0’)
Usage 3: Cin. Get (without parameters) No parameters are mainly used to discard the unnecessary characters in the input stream, or to discard carriage return to make up for the deficiency of Cin. Get (character array name, number of characters received) (because cin. Get () retains the newline character in the input buffer, cin.

3. Cin. Getline () // accepts a string and can receive Spaces and output
#include < iostream>
using namespace std;
main ()
{
char m[20];
cin. Getline (m, 5);
cout< < m< < endl;
}
Input: JKLJKLJKL
output: JKLJ
Accept 5 characters into m, the last of which is ‘\0’, so you only see 4 characters output;
If 5 is changed to 20:
input: JKLJKLJKL
output: JKLJKLJKL
JKLF FJLSJF FJSDKLF
output: JKLF FJLSJF FJSDKLF
Cin getline()
//cin. Getline () actually has three parameters, cin. Getline (accepts string storage space m, accepts 5, ending characters)
// when the third parameter is omitted, the system default is ‘\n’
// if cin. Getline () in the example is changed to cin. When JLKJKLJKL is input, JKLJ is output, while when jkaljkljkl is input, jk is output. At this point, the status flag bit of cin is false (as long as the number of inputs exceeds the number of accepts, cin. Clear () is needed if getline() is used afterwards,
Cin getLine (M [I],20) can also be used when using a multi-dimensional array.
#include< iostream>
#include< string>
using namespace std;

{
char m[3][20];
the for (int I = 0; i< 3; I++)
{
cout< <” \n Please enter “< < i+1< <” The string: “< < endl;
cin. Getline (m [I], 20);
}
Cout< < endl;
the for (int j = 0; j< 3; J++)
cout< <” Output m [” & lt; & lt; j< & lt; “] Value: “& lt; < m[j]< < endl;
}
Please enter the first string:
kskr1
Please enter the second string:
kskr2
Please enter the third string:
kskr3
Output m[0] value :kskr1
output m[1] value :kskr2
output m[2] value :kskr3
Getline () // getLine () // getLine () // getLine () // getLine () // getLine () // getLine () // getLine () // getLine () // getLine () String>”
#include< iostream>
#include< string>
using namespace std;
main ()
{
string STR;
getline (cin, STR);
cout< < str< < endl;
}
Input: JKLJKLJKL
output: JKLJKLJKL
Input: JKL JFKSLDFJ JKLSJFL
output: JKL JFKSLDFJ JKLSJFL
Cin is similar to Cin. Getline (), but cin. Getline () belongs to istream stream while getLine () belongs to String stream and is a different function

C++ string substr()

Common member function

< string>

std::string::substr

string substr (size_t pos = 0, size_t len = npos) const;

Produce substring
Returns a new one
A copy of the String object that is initialized to a substring of the String object.

The
substring is the part of the object that starts at character position pos and spans len characters (or up to the end of the string, whichever comes first).

parameter

pos

The position of the first character is copied as a substring.

this function returns an empty string if this is equal to the length of the string.

if this is greater than the length of the string, it will throw out_of_range.

note: the first character is represented as the value 0 (not 1).

len

The number of characters included in the subscript (if the string is short, as many characters as possible can be used as needed).

string :: non-profit value represents all characters up to the end of the string.

size_t is an unsigned integral type (the same as member type)
string::size_type).

The return value A
String Object with a substring of this object.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}
 

Output:

think live in details.

Reverse function: reverses container contents

The reverse function reverses the contents of a container, contained in < algorithm> In the library.
1. Function prototype
The reverse function is equivalent to the following code:

template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
     while ((first!=last)&&(first!=--last))
     {
          std::iter_swap (first,last);
          ++first;
     }
}

The reverse function swaps two elements using iter_swap.

2. Parameters: first and last
First and last are bidirectional iterators, and the scope of reverse function inversion is [first,last], so the elements pointed to by first are included, but the elements pointed to by last are not.
3. Return value
The reverse function returns no value.
Example 4,

// reverse algorithm example
#include <iostream>    
// std::cout
#include <algorithm>   
// std::reverse
#include <vector>      
// std::vector

int main () {
    std::vector<int> myvector;
    // set some values:
    for (int i=1; i<10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9
    std::reverse(myvector.begin(),myvector.end());    // 9 8 7 6 5 4 3 2 1
    // print out content:
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    return 0;
}

Output:

myvector contains: 9 8 7 6 5 4 3 2 1

5. Complexity

Iterate over the first and last elements. So the complexity is linear and the loop is half the length of the array.

Copy forbidden in C + +++

A common way to disallow copying classes is to define copy constructors and assignment functions as private functions, as shown in effective c++ :
Real estate agents sell houses, and software systems that serve such agents naturally have a class to represent the houses being sold:
class HomeForSale { … };
Every real estate agent is quick to point out that every property is unique — no two are exactly alike. In this case, the idea of making a copy for a HomeForSale Object is puzzling. How can you copy something unique?So it’s best to make things like this attempt to copy a HomeForSale Object non-compilable:
HomeForSale h1;
HomeForSale h2;
HomeForSale h3(h1);// attempt to copy the h1 – should
// not compile!
h1 = h2;// attempt to copy the h2 – should
// not compile!
Alas, the way to prevent this kind of compilation is not that straightforward. In general, if you don’t want a class to support some kind of functionality, you can simply not declare the function that gives it that functionality. This strategy does not work for copy constructor (copy constructor) or copy assignment operator (copy assignment operator) because, as indicated in Item 5, if you do not declare them and someone wants to call them, the compiler will declare them for you.
That limits you. If you do not declare copy constructor or copy assignment operator, the compiler can also generate them for you. Your class will also support copying. On the other hand, if you declare these functions, your classes will still support copying. During this period, our aim is to prevent copying!
The key to solving this problem is that all compiler generated functions are public. To prevent these functions from being generated, you have to declare them yourself, but you have no reason to declare them public. Instead, declare the copy constructor (copy constructor) and the copy assignment operator (copy assignment operator) private. By explicitly declaring a member function, you prevent the compiler from generating its own version, and by declaring the function private, you prevent others from calling it.
In general, this option is not very safe, as the member and friend functions can still call your private functions. In other words, unless you’re smart enough not to define them. So, when someone accidentally calls them, there will be an error at link-time. This technique – declaring member functions private yet deliberately failing to implement it – is indeed very good. In the iostreams library of C++, there are several classes using this method to prevent copying. For example, if you look at the definitions (definitions) of ios_base, basic_ios, and Sentry in your standard library implementation, you will see that the copy constructor (copy constructor) and the copy assignment operator (copy assignment operator) are declared private and are not defined.
To apply this trick to HomeForSale, it’s simple:
The class HomeForSale {
public:

Private:

HomeForSale (const HomeForSale&) ;// declarations only
HomeForSale& operator=(const HomeForSale&) ;
};
You’ll notice That I omitted the name functions’ parameters. It’s not necessary, it’s just a common practice. After all, functions are not implemented and are less likely to be used, so why specify parameter names?
For the above class Definition, the compiler will prevent a client from attempting to copy HomeForSale Objects, and if you accidentally do so in a Member or friend function, the linker will protest.
Will link – time error (connection) in advance to compile time is feasible after all, the discovery of the error (early than late found good), by not HomeForSale itself declared in the copy constructor (copy constructor) and copy the assignment operator (copy assignment operator) is a private, but in a to prevent copying (prevent copy) and specially designed base class (base class) in a statement. The base class itself is very simple:
Class Uncopyable {
protected:// allow construction
Uncopyable () {}// and destruction of
~ Uncopyable () {}// derived objects…
Private:
Uncopyable (const Uncopyable&) ;//… But prevent copying
Uncopyable& operator=(const Uncopyable&) ;
};
To prevent copying HomeForSale Objects, we must now make it inherit from Uncopyable:
Class HomeForSale: private Uncopyable {// class no longer
…// declares copy ctor or
};// copy the assign. Operator
This is done because if someone — even a member (member) or friend function (friend function) — tries to copy a HomeForSale Objects (object), the compiler will attempt to generate a copy constructor (copy constructor) and a copy assignment operator (copy assignment operator). As explained by Item 12, the compiler-generated versions of these functions attempt to call the corresponding functions of the Base class, and these calls are rejected because the copy operation is private in the Base class.
The implementation and use of Uncopyable contain subtlety. For example, inheritance from Uncopyable need not be public (see Items 32 and 39), and Uncopyable’s destructor need not be virtual (see Item 7). Because Uncopyable does not contain data, it meets the condition of Empty Base Class Optimization described by Item 39, but because it is a base class, multiple inheritance cannot be introduced for application of this technique (see Item 40). On the other hand, Multiple inheritance sometimes defies empty Base Class optimization (see Item 39 again). In general, you can ignore these subtleties and use Uncopyable only as demonstrated here, because it works like an advertisement. You can also use a version available in Boost (see Item 55). That class is called noncopyable. That’s a good thing, I just found that name a little UN – (no…) HMM… Nonnatural.

The usage and difference of atoi() and stoi() functions in C + +

Similarities:
The C++ character processing function, the numeric string into an int output
Header files are #include< cstring>
Difference:
Atoi () is const char*, so we must call c_str() to const char* for a string STR. Stoi () is const string*, const char* is not required.
As shown in figure:

Stoi () will do the scope check, the default scope is within the scope of int, if beyond the scope will be runtime error!
As shown in figure:

 
Atoi () will not check the range. If it exceeds the range, it will output the upper limit, and if it exceeds the lower limit, it will output the lower limit.
Code:

 
    //myfirst.cpp--displays a message #include "stdafx.h" #include < iostream> #include < set> #include < string> using namespace std; int main() { string s1 = "2147482", s2 = "-214748"; string s3 = "214748666666663", s4 = "-21474836488"; cout < < stoi(s1) < < endl; cout < < stoi(s2) < < endl; cout < < atoi(s3.c_str()) < < endl; cout < < atoi(s4.c_str()) < < endl; return 0; }

Console:

Vector delete pop of element_ back(),erase(),remove()

The member function pop_back() of vector can delete the last element.
The function Erase (), in turn, can remove elements that are indicated by an Iterator, as well as elements of a specified range.
— You can also use the generic algorithm remove() to remove elements in a vector container.
— The difference is: Remove generally does not change the size of the container, whereas member functions such as pop_back() and Erase () do.
1, pop_back ()

void pop_back();

Delete last element
Removes the last element in the
vector, effectively reducing the container
size by one.

This destroys the removed element.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> vec;
	int sum(0);
	vec.push_back(10);
	vec.push_back(20);
	vec.push_back(30);
	while(!vec.empty())
	{
		sum += vec.back();
		vec.pop_back();
	}
	cout<<"vec.size()="<<vec.size()<<endl;
	cout<<"sum = "<<sum<<endl;
	system("pause");
	return 0;
}

0

60
2、erase()
C++98

iterator erase (iterator position);
iterator erase (iterator first, iterator last);

C++11

iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);

Deletes an element in the specified location or deletes an element in the specified range
Removes from the vector of either a single element (position) or a range of elements ( [first, last) .) including the first, not including the last.

This effectively reduces the container size by the number of elements removed, which are destroyed.
It reduces the size of the container. After the iterator is used on the erase element, it subsequently fails, i.e., the iterator can no longer operate on the vector.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> vec;
	for(int i=0;i<10;i++)
	{
		vec.push_back(i);
	}
	vec.erase(vec.begin()+5);//erase the 6th element
	vec.erase(vec.begin(),vec.begin()+3);
	for(int i=0;i<vec.size();i++)
	{
		cout<<vec[i]<<' ';
	}
	cout<<endl;
	system("pause");
	return 0;
}

// Output 3, 4, 6, 7, 8, 9
3. Remove () Not recommended

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> vec;
	vec.push_back(100);
	vec.push_back(300);
	vec.push_back(300);
	vec.push_back(300);
	vec.push_back(300);
	vec.push_back(500);
	cout<<&vec<<endl;
	vector<int>::iterator itor;
	for(itor=vec.begin();itor!=vec.end();itor++)
	{
		if(*itor==300)
		{
			itor=vec.erase(itor);
		}
	}
	for(itor=vec.begin();itor!=vec.end();itor++)
	{
		cout<<*itor<<" ";
	}	
	system("pause");
	return 0;
}

C + + pauses the black window system (“pause”); (get ch(), getchar(), system (pause)’s connection and difference

In a c++ program, if it is a window, sometimes it will disappear with a flash. If you don’t want it to disappear, add:

system(“pause”);

Note: Do not add after the return statement, it will not be executed.

Analysis:

System () is a call to the system command;

pause pause command;

When run here, it will say “Press any key to continue…” or “Press any key to continue…” ;

In VS2008, can be called directly

VC 6.0, to add the following header file!

#include < stdlib.h>  
The

Supplement: http://bbs.csdn.net/topics/390231844

http://www.gidnetwork.com/b-61.html (the answer), 9/f,

1:

I don’t know why I often see people declare “void main” on CSDN

is not a standard entry point for C++

standard supports only two kinds of announcements

first type “int main”

int main(int argc, char *argv[]))

declares “void main” may have unexpected results

this doesn’t just apply to C++, C works as well

is this the textbook’s fault?Or is it the professors’ fault?

2:

do not use system(“pause”) to pause. Use STD ::cin. Get or getchar() instead.

why don’t you use system(“pause”)?

for two reasons

1: not portable
Two: it’s very expensive

where is it important?Let’s look at the process of system(“pause”)

1: pause your program

2: start the OS in the sub-process

3: finds the command to execute and allocates the memory for it

4: wait for input

5: recycle memory

6: end OS

7: continue your program

Getch () :
header file: conio. H
function purpose: read a character from the console, but not displayed on the screen
e.g. :
char ch; Or int ch;
getch (); Or ch = getch ();
with getch (); It waits for you to press any key before continuing with the following statement;
with ch = getch (); It waits for you to press any key, assigns the ASCII character to ch, and then executes the following statement.

getchar():
Extract characters from IO stream!
this function is declared in the stdio.h header file and used to include the stdio.h header file. Such as:
# include< stdio.h>
int getchar (void);
getch has the same basic functions as getchar, except that getch gets the key value directly from the keyboard and does not wait for the user to press enter. As soon as the user presses a key,
getch returns immediately. Getch returns the ASCII code entered by the user and returns -1 on error. The
getch function is commonly used in program debugging. During debugging, the relevant results are displayed in a critical position for viewing, and then the getch function is used to pause the program,
when any key is pressed after the program continues to run.

the first is that the two functions exist in different header files, this one basically you write #include< stdio.h> Getchar (), can accept a character, press enter to end, and display on the screen, and can clear forward just write
2. Getch (), receive a character, on the screen does not show
you write more, practice should be understood
Getchar () gets a character from the input device that is displayed on the screen, getch gets a character from the input device,
but the character is not displayed on the screen, for example:
#include < stdio.h>
int main()
{
printf(“%c”,getchar()); Suppose you get a character f from the keyboard here and press enter and you’ll see something like this
f
f
the first f is the f that you typed in, the second f is the f that printf gets
#include < stdio.h>

int main () {
printf (” % c “, getchar ());
}
suppose you enter an f and the result is
f this f is the printf output f
getchar is optimized,
getchar input character, until you press enter, then execute the code
getch without hitting enter
System (“pause”) can freeze the screen to observe the execution results of the program.
getch can not only pause the program
but also get a character
system(“pause”) is just a simple pause
the difference is the mechanism of action, although the effect looks the same. The
system return value is the result after you call the Shell command, and the getch() function will return the result provided by the function.
usually, the return value of Shell command may be unexpected and uncertain. Sometimes, it is impossible to judge whether the command
is executed successfully through the return value, which will have an impact on the program that conducts subsequent processing according to the return value. The return value of the function determines whether the
line is held successfully. But you don’t judge the return value at all, and you don’t process it, so you don’t have to worry about these differences.

C++ cin.ignore Use of ()

The function of CIN. Sync () is to clear the buffer, while cin. Ignore () is also used to delete the data in the buffer, but it has more accurate control over the deleted data in the buffer.
Cin. Ignore () can be used if you want to take only one part of the buffer and discard the other.
cin.ignore(int intExp, char chExp);
Where intExp is an integer expression, or it can be an integer value that represents the maximum number of characters that can be ignored in a line, such as intExp=100; There is also a parameter, chExp, which is a character expression. Ignore () if you come across a character that equals chEXP, and if you don’t get chEXP after ignoRE100, just stop ignore(), so 100 is the maximum number of characters that ignore().
here are some examples

#include<iostream>
#include<cstdlib>
int main()
{
  int ival1 = 0, ival2 = 0;
  std::cin >> ival1;
  std::cin.ignore(100, '\n');
  std::cin >> ival2;
  std::cout << "ival1 = " << ival1 << std::endl;
  std::cout << "ival2 = " << ival2 << std::endl;
  system("pause");
  return 0;
}


After you press Enter, Ival1 receives 12, the rest is cleared, because Enter is itself a blank line, and then the input stream will wait for the second input to assign a value to ival2. The if there is no middle the STD: : cin. Ignore (100), '\ n') , will not wait for the second input, output ival1 = 12 ival2 = 34 directly:

Ignore (2, '\n')
STD ::cin. Ignore (100, ‘\n’) STD ::cin. Ignore (2, ‘\n’), after ival1 receives 12, ignore will clear two characters:

Why is iVAL2 4 instead of 78?
Because the IO objects we use are cin cout manipulation char data, no matter what data we input, cin cout will be transformed into char for processing, for example, we want to output the value of a plastic variable, then before the output, cout will turn the value of the variable into characters, in the output (C++ Primer Plus In essence, the c + + insertion operator adjusts its behaviors to fit the type of data that follows it.), so ignore to clear out a space above and one character at a time, so the remaining 4, 56, 78, the buffer so ival2 is equal to 4.
(3) If cin. Ignore () does not give the parameter, the default parameter is cin. Ignore (1,EOF), that is, one character before EOF will be cleared out.

Three kinds of errors in C + + program

There are two types of errors that often occur when debugging our programs.
One is the compilation error; the other is the runtime error. The other is The Semantics error.
The compilation error is a kind of error that occurs when we compile the program, primarily due to syntax errors, or errors in the use of data types. The Runtime error is when our program compiles, the link passes, but an error occurs while running. The Runtime error is more difficult to catch, because the compiler doesn’t tell you what the error is. The Semantics error originates from the wrong understanding of the problem and the solution. Procedure okay, but the way to solve the problem is to have the wrong mouth.

Error: global variable is ambiguous (conflict between using namespace STD and global variable)

When you recursively write eight queens, you define a global variable count, which results in the following problem: global variables are not clear.



Finally, I found that in the implementation file.CPP, I used using NAMESPACE STD;
Solutions:
1. Use count instead of ::count (because STD ::count is also in the STD namespace, the compiler is not sure if it is ::count or STD ::count)
Comment out the namespace
3. Or:
using std::cout;
using std::endl;
using std::cin;

Reflection summary:
I. Thinking using NAMESPACE STD
A lot of times it’s not a good idea to use this code (and more importantly: it’s best not to use it in header files)
A good habit is to use STD ::cout and STD ::cin
All the identifiers of the c + + standard library is defined in a namespace called STD, using namespace STD is to import all the system defined identifier, because of the standard library is very large, the programmer when choosing the name of a class or function name is probably has one of the same name, and the standard library that is your own definition of things (variables, methods, classes, etc.) and the system of the identifier name repetition, otherwise there will be a naming conflict error!
C++ definition of global variables
1. It is generally a good idea to declare global variables in a CPP file (if defined in a.h file, multiple layers contain errors that may cause duplication of definitions)
2. Once defined in CPP, you can use the extern keyword in the.h file for an extern declaration (the extern declaration represents the declaration that an externally defined variable is introduced here, rather than another local variable with the same name being declared in this compilation unit)
Then, when other files want to use these variables, just the #include header file is fine, and it won’t cause a double-definition error

3. Comparison of static global variables, global constants (CONST) and ordinary global variables:
1. Static global variables: They can’t be introduced with extern, i.e., extern and static cannot be used together. And static globals are quite different from normal globals.
Static modification of the scope of a global variable is just its own compilation unit (in this compilation unit changes to take effect), when used in other units, the variables have a new memory address, that is, each compilation unit USES it to it opened up a separate space, and make a copy of its original value, so if a unit to modify it, then its value in multiple compilation unit may not be the same

Note:
The static modifier is static, static, static, static, static, static, static, static, static, static, static.
Multiple units contain the static global header file, which doesn’t cause a redefinition error because each unit creates a new space to store it.
2. Global const variable: const like common global variables, global variables to use in a. CPP and initialization, defined in. H header file using extern declaration, then you need to use the place contains. H, its memory address is also different in the multiple compilation unit (this is similar to the static global variable), but because of is constant, not modify the value, so even if the memory address didn’t influence, different values are the same.

Also useless to, refer to: http://blog.csdn.net/jiadebin890724/article/details/40509333

Four, the use of namespaces
To be continued…