我已经告诉别人,编写using namespace std;代码是错误的,我应该用std::cout和std::cin直接代替.
为什么被using namespace std;认为是不好的做法?是低效还是冒着声明模糊变量(与名称std空间中的函数具有相同名称的变量)的风险?它会影响性能吗?
在C++中,有一种简单的方法:
这个std :: string
\t\tHELLO WORLD\r\nHELLO\t\nWORLD \t
Run Code Online (Sandbox Code Playgroud)
成:
HELLOWORLDHELLOWORLD
Run Code Online (Sandbox Code Playgroud) 我有这个代码删除std :: string中的空格,它删除空格后的所有字符.所以,如果我有"abc def",它只返回"abc".如何让它从"abc def ghi"变为"abcdefghi"?
#include<iostream>
#include<algorithm>
#include<string>
int main(int argc, char* argv[]) {
std::string input, output;
std::getline(std::cin, input);
for(int i = 0; i < input.length(); i++) {
if(input[i] == ' ') {
continue;
} else {
output += input[i];
}
}
std::cout << output;
std::cin.ignore();
}
Run Code Online (Sandbox Code Playgroud) 根据C11 WG14草案版本N1570:
标头
<ctype.h>声明了几个用于分类和映射字符的函数.在所有情况下,参数都是aint,其值应表示为unsigned char或等于宏的值EOF.如果参数具有任何其他值,则行为未定义.
是不确定的行为?:
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
int main(void) {
char c = CHAR_MIN; /* let assume that char is signed and CHAR_MIN < 0 */
return isspace(c) ? EXIT_FAILURE : EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
标准是否允许传递char给isspace()(char到int)?换句话说,char转换后可以int 表示为unsigned char?
能够代表.
是char能够被表示为unsigned char?是的.§6.2.6.1/ 4:
存储在任何其他对象类型的非位字段对象中的值由n
×CHAR_BIT …
因此,我在这个网站上看到了很多解决方案以及有关从 C++ 文本文件中读取内容的教程,但尚未找到解决我的问题的方法。我是 C++ 新手,所以我认为我在拼凑一些文档以理解这一切方面遇到了困难。
我想做的是读取文本文件编号,同时忽略文件中用“#”表示的注释。因此,示例文件如下所示:
#here is my comment
20 30 40 50
#this is my last comment
60 70 80 90
Run Code Online (Sandbox Code Playgroud)
当没有任何注释时,我的代码可以很好地读取数字,但我不明白如何很好地解析流以忽略注释。现在它是一种黑客解决方案。
/////////////////////// Read the file ///////////////////////
std::string line;
if (input_file.is_open())
{
//While we can still read the file
while (std::getline(input_file, line))
{
std::istringstream iss(line);
float num; // The number in the line
//while the iss is a number
while ((iss >> num))
{
//look at the number
}
}
}
else
{
std::cout << "Unable to open …Run Code Online (Sandbox Code Playgroud) 我使用以下内容从我的变量中删除空格
for (i=0, ptr=lpsz;ptr[i];ptr++)
{
if (*ptr == ' ')
i++;
*ptr = ptr[i];
}
*ptr=0;
Run Code Online (Sandbox Code Playgroud)
当有多个空间时似乎有问题而且我不确定我做错了什么.有人可以帮我吗?