将字符串格式化为C中的列

时间:2017-03-25 22:18:15

标签: c string printf string-formatting

我遇到一个问题,即尽管字符串的大小是多少,但仍然可以很好地将这个字符串输入到列中。我尝试了不同的格式和其他东西;它只是不工作。函数的工作方式是在#pragma once #include<iostream> using namespace std; class String { private: int size; char* str; public: String(); ~String(); String(char* arr); String(const String& copy); int sizeStr(); friend ostream& operator << (ostream& output, const String& outputStr); friend istream& operator >> (istream& input, String& inputStr); }; String::String() { this->size = 0; this->str = nullptr; } String::String(char* str) { this->size = strlen(str); this->str = new char[size]; for (int i = 0; i < size; i++) { this->str[i] = str[i]; } } String::~String() { delete[] str; } String::String(const String& copy) { if (this != &copy) { this->size = copy.size; this->str = new char[size]; for (int i = 0; i < size; i++) { this->str[i] = copy.str[i]; } } } int String::sizeStr() { return this->size; } ostream& operator << (ostream& output, const String& outputStr) { for (int i = 0; i < outputStr.size; i++) { output << outputStr.str[i]; } return output; } istream& operator >> (istream& input, String& inputStr) { return input; } 工作之前,还有另一个函数可以更新你在下面看到的所有字符串变量,所以我猜这可能是问题所在。我想。

printCompanyTable

1 个答案:

答案 0 :(得分:1)

除了link提供的Japu_D_Cret中接受的答案外,如果您使用%-30s,它会将字符串格式化为30个字符但如果字符串更长,则会打印所有这一切...

试试这个:

printf_s("%s %s %f %-30.30s %-30.30s %s\n", companyId, companyNameLookup, discountRateLookup, discount, tax, pickUpBayLookup);

使用.表示它会将字符串格式化为30个字符,-表示字符串将左对齐(默认为右对齐)。

编辑:调整代码以反映@Jonathan Leffler所做的更正